Uva--572 (DFS)

2014-07-02 00:08:31

题意&思路:连通块问题,DFS搞之。

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <string>
 4 #include <cstring>
 5 #include <sstream>
 6 #include <cmath>
 7 using namespace std;
 8 
 9 int cnt,m,n,g[105][105],vis[105][105];
10 
11 void Dfs(int r,int c){
12     if(r < 0 || r >= m || c < 0 || c >= n || vis[r][c] || !g[r][c]) return;
13     vis[r][c] = 1;
14     Dfs(r - 1,c - 1); Dfs(r - 1,c); Dfs(r - 1,c + 1);
15     Dfs(r,c - 1);                   Dfs(r,c + 1);
16     Dfs(r + 1,c - 1); Dfs(r + 1,c); Dfs(r + 1,c + 1);
17 }
18 
19 int main(){
20     char tmp[105];
21     while(cin >> m >> n){
22         if(m == 0) break;
23         memset(vis,0,sizeof(vis));
24         cnt = 0;
25         for(int i = 0; i < m; ++i){
26             cin >> tmp;
27             for(int j = 0; j < n; ++j)
28                 g[i][j] = tmp[j] == '@' ? 1 : 0;
29         }
30         for(int i = 0; i < m; ++i){
31             for(int j = 0; j < n; ++j){
32                 if(!vis[i][j] && g[i][j]){
33                     Dfs(i,j);
34                     ++cnt;
35                 }
36             }
37         }
38         printf("%d\n",cnt);
39     }
40     return 0;
41 }

 

posted @ 2014-07-02 00:09  Naturain  阅读(113)  评论(0)    收藏  举报