Problem Description
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.
Input
The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either *', representing the absence of oil, or
@’, representing an oil pocket.
Output
For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
Sample Input
1 1
*
3 5
@@*
@
@@*
1 8
@@**@*
5 5
**@
@@@
@*@
@@@*@
@@**@
0 0
Sample Output
0
1
2
2
解題思路:
經典的dfs , 其中有一點要非常注意,就是題中所說的相連不只是上下左右四個方向,應該還包含左上、左下、右上、右下在內的8個方向。
代碼:
#include <cstdio>
#include <string.h>
using namespace std;
char map[105][105];
int visited[105][105];
int dir[8][2] = {0 , 1 , 1 , 0 , 0 , -1 , -1 ,0 , -1 , -1 , 1, 1 , 1, -1 , -1 , 1}; //移動方向
int m , n , ans = 0;
void dfs(int i , int j){
int k ;
if(i > m || j > n || i < 1 || j < 1){
return;
}
visited[i][j] = 1;
for(k = 0 ; k < 8 ; k ++){
int tempi = i + 1 * dir[k][0];
int tempj = j + 1 * dir[k][1];
if(visited[tempi][tempj] == 0 && map[tempi][tempj] == '@'){
visited[tempi][tempj] = 1;
dfs(tempi , tempj);
}
}
}
int main(){
int i , j;
while(scanf("%d %d",&m ,&n) != EOF){
if(m == 0 && n == 0)
break;
ans = 0;
memset(map , '*' , sizeof(map));
memset(visited , 0 , sizeof(visited));
for(i = 1 ; i <= m ; i ++){
getchar(); //用來接收回車鍵 , 否則回車鍵會被認爲是一個字符計入map數組
for(j = 1 ; j <= n ; j++){
scanf("%c" , &map[i][j]);
}
}
for(i = 1 ; i <= m ; i ++)
for(j = 1 ; j <= n ; j ++){
if(visited[i][j] == 0 && map[i][j] == '@'){
ans ++; //重新開始新的一輪尋找,表明上一個連續塊已經尋找結束
dfs(i , j );
}
}
printf("%d\n",ans);
}
return 0;
}