http://hncu.acmclub.com/index.php?app=problem_title&id=111&problem_id=1103
小明站在一个矩形房间里,这个房间的地面铺满了地砖,每块地砖的颜色或是红色或是黑色。小明一开始站在一块黑色地砖上,并且小明从一块地砖可以向上下左右四个方向移动到其他的地砖上,但是他不能移动到红色地砖上,只能移动到黑色地砖上。
请你编程计算小明可以走到的黑色地砖最多有多少块。
输入包含多组测试数据。
每组输入首先是两个正整数W和H,分别表示地砖的列行数。(1<=W,H<=20)
接下来H行,每行包含W个字符,字符含义如下:
‘.’表示黑地砖;
‘#’表示红地砖;
‘@’表示小明一开始站的位置,此位置是一块黑地砖,并且这个字符在每组输入中仅会出现一个。
当W=0,H=0时,输入结束。
对于每组输入,输出小明可以走到的黑色地砖最多有多少块,包括小明最开始站的那块黑色地砖。
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
45
59
6
13
思路:简单的搜索,BFS,DFS皆可
DFS:
#include <stdio.h> #include <string.h> int n,m,sx,sy,cnt; int to[4][2] = {1,0,-1,0,0,1,0,-1}; char map[25][25]; void dfs(int i,int j) { int x,y,k; cnt++; map[i][j] = '#'; for(k = 0;k<4;k++) { x = i+to[k][0]; y = j+to[k][1]; if(x>=0 && y>=0 && x<m && y<n && map[x][y]=='.') dfs(x,y); } return ; } int main() { int i,j; while(~scanf("%d%d%*c",&n,&m),n+m) { for(i = 0;i<m;i++) { for(j = 0;j<n;j++) { scanf("%c",&map[i][j]); if(map[i][j] == '@') { sx = i; sy = j; } } getchar(); } cnt = 0; dfs(sx,sy); printf("%d\n",cnt); } return 0; }
BFS:
#include <stdio.h> #include <string.h> #include <queue> using namespace std; struct node { int x,y; }; char map[25][25]; int vis[25][25]; int n,m,sx,sy,ans; int to[4][2]= {1,0,-1,0,0,1,0,-1}; int check(int x,int y) { if(x<0 || y<0 || x>=m || y>=n) return 1; if(vis[x][y] || map[x][y] == '#') return 1; return 0; } void bfs() { int i; queue<node> Q; node a,next; ans = 0; a.x = sx; a.y = sy; vis[sx][sy] = 1; Q.push(a); while(!Q.empty()) { ans++; a = Q.front(); Q.pop(); for(i = 0; i<4; i++) { next = a; next.x+=to[i][0]; next.y+=to[i][1]; if(check(next.x,next.y)) continue; vis[next.x][next.y] = 1; Q.push(next); } } } int main() { int i,j,flag; while(~scanf("%d%d",&n,&m),n+m>0) { flag = 0; for(i = 0; i<m; i++) scanf("%s",map[i]); for(i = 0; i<m; i++) { for(j = 0; j<n; j++) { if(map[i][j]=='@') { sx = i; sy = j; flag = 1; break; } } if(flag) break; } memset(vis,0,sizeof(vis)); bfs(); printf("%d\n",ans); } return 0; }