首页 > 代码库 > POJ-2386-Lake Counting

POJ-2386-Lake Counting

 

比较简单的一道深搜题目,适合练手

 1 //题目链接: http://poj.org/problem?id=2386
 2 //解题思路:将湖泊定义为1, 陆地定义为0, dfs搜索每个点即可
 3 #include <stdio.h>
 4 #include <string.h>
 5 
 6 int map[110][110], vis[110][110];       //map模拟地图,vis用于标记是否访问过
 7 int dir[8][2] = {{-10}, {-11}, {01}, {11}, {10}, {1, -1}, {0, -1}, {-1, -1}};           //八个方向
 8 int n, m;
 9 
10 void dfs(int x, int y){
11         int i, j;
12         if(map[x][y] == 0 || vis[x][y] == 1)    return ;        //已访问或者当前位置为空
13         vis[x][y] = 1;                                          //标记点(x, y)已访问过
14         for(i = 0; i < 8; i++){
15                 dfs(x + dir[i][0], y + dir[i][1]);      //递归访问八个方向
16         }
17 }
18 
19 int main(){
20         int i, j;
21         char str[110];
22         int ans;
23         while(scanf("%d %d", &n, &m) != EOF){
24                 memset(map, 0sizeof(map));    //所有格子初始化为陆地,包括周围的一圈
25                 memset(vis, 0sizeof(vis));            //所有点初始化为未访问状态
26                 for(i = 1; i <= n; i++){
27                         scanf("%s", str);
28                         for(j = 1; j <= m; j++){
29                                 if(str[j - 1] == W){          //‘w‘ 为1,‘ .‘为0
30                                         map[i][j] = 1;
31                                 }
32                                 else{
33                                         map[i][j] = 0;
34                                 }
35                         }
36                 }
37                 ans = 0;
38                 for(i = 1; i <= n; i++){
39                         for(j = 1; j <= m; j++){
40                                 if(map[i][j] == 1 && vis[i][j] == 0){   //dfs搜索所有未访问过的点
41                                         ans++;
42                                         dfs(i, j);
43                                 }
44                         }
45                 }
46                 printf("%d\n", ans);
47         }
48         return 0;

49 }

POJ-2386-Lake Counting