GeoSurvComp Geological Survey is responsible for detecting underground oil reserves. GeoSurvComp now detects oil in a rectangular area and divides the large area into many small pieces. They use specialized equipment to analyze whether oil is stored in each piece. If these small squares of oil are adjacent, they are considered part of the same reservoir. In this rectangular area, there may be many reservoirs. Your task is to determine how many different reservoirs there are.
Input
The input may have multiple rectangular areas (i.e., multiple sets of tests). The starting row of each rectangular region contains M and n, representing the number of rows and columns, 1 <= n, m <== 100. If m =0 indicates the end of the input, then n rows, M characters per row. Each character corresponds to a small square and is either'*', which means there is no oil, or'@', which means there is oil.
Output
For each rectangular area, the number of output reservoirs. Two small squares are adjacent, if and only if they are adjacent to each other horizontally or vertically or diagonally (that is, eight directions).
Sample Input
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@@
@@**@
0 0
Sample Output
0
1
2
2
thinking
The most basic dfs calculates the connected components, paying attention to checking the boundary and whether it is an oil field or not.
Code
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); } } }