Write a program to count the number of black tiles which he can reach by repeating the moves described above.
InputThe input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
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)
OutputFor each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
Sample Output
45 59 6 13
题目的大意就是搜图判断最多能遍历多少个".";简单dfs
#include<iostream> #include<cstring> using namespace std; int w,h,ans; char arr[25][25]; int mark[25][25]; int d[4][2]={{1,0},{0,1},{0,-1},{-1,0}}; void dfs(int x,int y) { mark[x][y]=1; for(int i=0;i<4;i++){ int dx=x+d[i][0]; int dy=y+d[i][1]; if(dx>=0&&dy>=0&&dx<h&&dy<w&&mark[dx][dy]==0&&arr[dx][dy]=='.'){ ans++; mark[dx][dy]=1; dfs(dx,dy); } } } int main() { while(cin>>w>>h){ memset(mark,0,sizeof(mark)); ans=1; if(w==0&&h==0) break; for(int i=0;i<h;i++){ scanf("%s",&arr[i]); } for(int i=0;i<h;i++) for(int j=0;j<w;j++){ if(arr[i][j]=='@'){ // mark[i][j]=1; dfs(i,j); } } cout<<ans<<endl; } return 0; }
BFS也可以写就是只要是x周围存在"."就加1,
#include<iostream> #include<queue> #include<cstring> using namespace std; char arr[22][22]; int sa,ea; int n,m; int v[22][22]={0}; struct stu{ int a,b; // int sum; }; int a[4]={0,1,0,-1}; int b[4]={1,0,-1,0}; void bfs() { int ans=0; // priority_queue<stu >que; queue<stu>que; stu q1; q1.a=sa; q1.b=ea; // q1.sum=1; v[sa][ea]=1; que.push(q1); while(que.size()){ stu h; // h=que.top(); h=que.front(); que.pop(); stu d; for(int i=0;i<4;i++){ d.a=h.a+a[i]; d.b=h.b+b[i]; if(d.a>=0 && d.b>=0 && d.a<m && d.b<n&& v[d.a][d.b]!=1 && arr[d.a][d.b]!='#'){ v[d.a][d.b]=1; // d.sum=h.sum+1; // cout<<d.sum<<endl; que.push(d); // ans=max(ans,d.sum); ans++;//只要加入到队列中就加一,因为加入到队列的一定是'.' } } } cout<<ans+1<<endl; } int main(){ while(cin>>n>>m) { memset(v,0,sizeof(v)); if(n==0&&m==0) break; for(int i=0;i<m;i++){ scanf("%s",&arr[i]); } for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(arr[i][j]=='@'){ sa=i; ea=j; } } } bfs(); } return 0; }