There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move
only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
45 59 6 13
解题思路:这是一道bfs的题目,在每次push的时候,就将答案加一
代码:
#include<iostream> #include<queue> #include<cstring> using namespace std; int hang,lie; char a[25][25]; int vis[25][25]; int dis[][2] = {{1,0},{0,1},{-1,0},{0,-1}}; struct node { int x; int y; }; int ok(int aa,int b) { if(aa>=0&&aa<hang&&b>=0&&b<lie&&a[aa][b]=='.') return true; else return false; } int bfs(node now) { int ans = 0; node help ; node help2 ; queue<node> q; q.push(now); vis[now.x][now.y] = 1; while(!q.empty()) { help = q.front(); q.pop(); for(int i = 0;i<4;i++) { help2.x = help.x+dis[i][0]; help2.y = help.y+dis[i][1]; if(!vis[help2.x][help2.y]&&ok(help2.x,help2.y)) { q.push(help2); vis[help2.x][help2.y] = 1; ans++; } } } return ans; } int main() { while(cin>>lie>>hang) { if(lie==0||hang==0) break; memset(vis,0,sizeof(vis)); node pos ; for(int i = 0;i<hang;i++) for(int j = 0;j<lie;j++) { cin>>a[i][j]; if(a[i][j]=='@') { pos.x = i; pos.y = j; } } int re = bfs(pos); cout<<re+1<<endl; } }