标签:
题目大意:
一块地为矩形,分成许多瓷砖。你站在一块黑色瓷砖上,只能走到周围相连的黑瓷砖上,问你总共能走过多少块瓷砖?(包括你最初站立的那块瓷砖)
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
(@为你站立的位置,.为黑瓷砖,#为其他)
Sample Output
45 59 6 13
简单的深度优先搜索题,代码如下
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 5 int dir[][2] = {{0,1}, {0,-1},{-1,0},{1,0}}; 6 int w, h; 7 8 char tiles[22][22]; 9 int flag[22][22]; 10 int ans; 11 void dfs(int x, int y) { 12 for(int i = 0; i < 4; i++) { 13 int tpx = x + dir[i][0]; 14 int tpy = y + dir[i][1]; 15 if(tpx >= 0 && tpy >= 0 && tpx < h && tpy < w && flag[tpx][tpy] == 0 && tiles[tpx][tpy] == ‘.‘) { 16 flag[tpx][tpy] = 1; 17 ans++; 18 dfs(tpx, tpy); 19 } 20 } 21 } 22 int main(int argc, char const *argv[]) 23 { 24 freopen("input.txt","r",stdin); 25 while(scanf("%d %d",&w, &h) != EOF && (w != 0 && h != 0)) { 26 for(int i = 0; i < h; i++) { 27 scanf("%s",tiles[i]); 28 } 29 int x0, y0; 30 for(int i = 0; i < h; i++) { 31 for(int j = 0; j < w; j++) { 32 if(tiles[i][j] == ‘@‘) { 33 x0 = i, y0 = j; 34 break; 35 } 36 } 37 } 38 memset(flag, 0, sizeof(flag)); 39 ans = 1; 40 flag[x0][y0] = 1; 41 dfs(x0, y0); 42 printf("%d\n",ans); 43 } 44 return 0; 45 }
标签:
原文地址:http://www.cnblogs.com/jasonJie/p/5800890.html