当前位置: 代码迷 >> 综合 >> POJ-1979
  详细解决方案

POJ-1979

热度:20   发布时间:2024-01-24 23:59:47.0

题目
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.
Input
The 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)
The end of the input is indicated by a line consisting of two zeros.
Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
题目大意
有一个N*M的矩阵,每个格子为’.’,’#‘或’@’。其中@为起点,’#‘不能走,’.'可以走。求一个人从@点出发,能走多少个格子。
解题思路
用搜索把人走过的格子标记,最后再统计格子的个数。
代码实现

#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
int dx[]={0,0,-1,1};
int dy[]={-1,1,0,0};
int a[101][101];
bool sym[101][101];
queue <int> X,Y;
int n,m;
void BFS(int xxx,int yyy)
{X.push(xxx);Y.push(yyy);sym[xxx][yyy]=true;while (!X.empty()){int x=X.front();int y=Y.front();X.pop();Y.pop();for (int i=0;i<4;i++){int xx=x+dx[i];int yy=y+dy[i];if (xx<1 || xx>n || yy<1 || yy>m || sym[xx][yy] || a[xx][yy]!=1) continue;sym[xx][yy]=true;X.push(xx);Y.push(yy);}}
}
int main()
{while (true){scanf("%d%d",&m,&n);if (n==0 && m==0) break;memset(a,0,sizeof(a));memset(sym,false,sizeof(sym));int x,y;for (int i=1;i<=n;i++) for (int j=1;j<=m;j++){char ch;cin>>ch;if (ch=='.') a[i][j]=1;if (ch=='@'){a[i][j]=1;x=i;y=j;}}BFS(x,y);int ans=0;for (int i=1;i<=n;i++)for (int j=1;j<=m;j++)if (sym[i][j]) ans++;printf("%d\n",ans);    }
}