http://poj.org/problem?id=1979
DFS模板题.
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 int W,H; 5 char map[22][22]; 6 int count=0; 7 bool check(int x,int y) 8 { 9 if(!(1<=x&&x<=H&&1<=y&&y<=W)) return false; 10 return true; 11 } 12 void dfs(int x,int y) 13 { 14 if(!check(x,y)) return ; 15 if(map[x][y]=='.'||map[x][y]=='@') { 16 count++; 17 map[x][y]='#'; 18 dfs(x,y-1); 19 dfs(x-1,y); 20 dfs(x,y+1); 21 dfs(x+1,y); 22 } 23 } 24 int main() 25 { 26 while(scanf("%d%d",&W,&H)!=EOF) { 27 if(W==H&&W==0) return 0; 28 int i,j,start_x,start_y; 29 for(i=1;i<=H;i++) { 30 getchar(); 31 for(j=1;j<=W;j++) { 32 scanf("%c",&map[i][j]); 33 if(map[i][j]=='@') { 34 start_x=i; 35 start_y=j; 36 } 37 } 38 } 39 count=0; 40 dfs(start_x,start_y); 41 printf("%d\n",count); 42 } 43 }