GeoSurvComp地质调查公司负责探测地下石油储藏。 GeoSurvComp现在在一块矩形区域探测石油,并把这个大区域分成了很多小块。他们通过专业设备,来分析每个小块中是否蕴藏石油。如果这些蕴藏石油的小方格相邻,那么他们被认为是同一油藏的一部分。在这块矩形区域,可能有很多油藏。你的任务是确定有多少不同的油藏。
Input
输入可能有多个矩形区域(即可能有多组测试)。每个矩形区域的起始行包含m和n,表示行和列的数量,1<=n,m<=100,如果m =0表示输入的结束,接下来是n行,每行m个字符。每个字符对应一个小方格,并且要么是’*’,代表没有油,要么是’@’,表示有油。
Output
对于每一个矩形区域,输出油藏的数量。两个小方格是相邻的,当且仅当他们水平或者垂直或者对角线相邻(即8个方向)。
Sample Input
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@@
@@**@
0 0
Sample Output
0
1
2
2
思路
最基本的dfs计算连通分量,注意检查边界及是否为油田即可。
代码
import java.util.Scanner;
public class HDU1241 {
private static int row, col;
private static boolean[][] data;
private static boolean[][] marked;
private static void dfs(int i, int j){
if(!data[i][j]) return;
marked[i][j] = true;
if(i + 1 < row && !marked[i + 1][j]) dfs(i + 1, j);
if(i - 1 >= 0 && !marked[i - 1][j]) dfs(i - 1, j);
if(j + 1 < col && !marked[i][j + 1]) dfs(i,j + 1);
if(j - 1 >= 0 && !marked[i][j - 1]) dfs(i,j - 1);
if(i + 1 < row && j + 1 < col && !marked[i + 1][j + 1]) dfs(i + 1, j + 1);
if(i + 1 < row && j - 1 >= 0 && !marked[i + 1][j - 1]) dfs(i + 1, j - 1);
if(i - 1 >= 0 && j + 1 < col && !marked[i - 1][j + 1]) dfs(i - 1, j + 1);
if(i - 1 >= 0 && j - 1 >= 0 && !marked[i - 1][j - 1]) dfs(i - 1, j - 1);
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while (true){
row = in.nextInt();
col = in.nextInt();
if(row == 0 && col == 0) break;
int count = 0;
in.nextLine();
data = new boolean[row][col];
marked = new boolean[row][col];
for(int i = 0; i < row; i++){
char[] c = in.nextLine().toCharArray();
for(int j = 0; j < col; j++){
data[i][j] = c[j] == '@';
}
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(!marked[i][j] && data[i][j]){
dfs(i, j);
count++;
}
}
}
System.out.println(count);
}
}
}