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