http://acm.hdu.edu.cn/showproblem.php?pid=2952
dfs
我的代码
1 #include <stdio.h>
2 #include <string.h>
3 const int N=110;
4 const int dx[4]={1,0,-1,0};
5 const int dy[4]={0,1,0,-1};
6 char maze[N][N];
7 bool vis[N][N];
8 int n,m;
9 void dfs(int x,int y)
10 {
11 vis[x][y]=1;
12 int d,nx,ny;
13 for (d=0;d<4;d++)
14 {
15 nx=x+dx[d]; ny=y+dy[d];
16 if (nx<0 || nx>=n || ny<0 || ny>=m || maze[nx][ny]!='#' || vis[nx][ny])
17 continue;
18 dfs(nx,ny);
19 }
20 }
21 int main()
22 {
23 int T;
24 scanf("%d",&T);
25 int i,j,cnt;
26 while (T--)
27 {
28 cnt=0;
29 memset(vis,0,sizeof(vis));
30 scanf("%d%d",&n,&m);
31 for (i=0;i<n;i++) scanf("%s",maze[i]);
32 for (i=0;i<n;i++)
33 for (j=0;j<m;j++)
34 if (maze[i][j]=='#' && !vis[i][j])
35 {
36 cnt++;
37 dfs(i,j);
38 }
39 printf("%d\n",cnt);
40 }
41 }