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 613
思路:
算是模板题吧,很水,不过也要注意下x,y轴要时刻对应,本博主就是在这个地方找了好久。。
把走过的‘.’变成‘#’,包括‘@’,然后就是模板了。
算是总结吧,x轴是从上往下的,就是行,y轴是从左到右的,即是列。
代码:
#include<algorithm> #include<stdio.h> #include<string.h> #include<math.h> #include<iostream> #include<queue> using namespace std; char map[25][25]; int d[4][2]= {{1,0},{-1,0},{0,1},{0,-1}}; int n,m; struct node { int x,y; } q,p; bool check(int p,int pp) { if(p<0||pp<0||p>=m||pp>=n||map[p][pp]=='#') return 0; return 1; } void bfs(int qwe) { queue<node> que; que.push(q); while(!que.empty()) { q=que.front(); que.pop(); for(int i=0; i<4; i++) { p.x=q.x+d[i][0]; p.y=q.y+d[i][1]; if(check(p.x,p.y)) { qwe++; map[p.x][p.y]='#'; que.push(p); } } } printf("%d\n",qwe); } int main() { while(~scanf("%d%d%*c",&n,&m),n&&m) { memset(map,0x00,sizeof(map)); int qwe=1; for(int i=0; i<m; i++) scanf("%s",&map[i]); for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(map[i][j]=='@') { q.x=i,q.y=j; map[i][j]='#'; break; } } } bfs(qwe); } }