Problem Description
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)
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).
题意:给出一个矩阵,包含起点‘@’和‘.’, ‘#’, 求从起点开始,能够经过多少个‘.’,‘#’不能走
思路:①DFS…遍历矩阵,从起点开始遍历,遇到一个点就将答案加1,直到无法遍历或遍历完成为止,输出答案。
② BFS,
代码:
DFS
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
char way[30][30];//定义一个二维数组来储存输入的数据
int vis[30][30]={0};//这是一个判断某一个格子有没有走过的数组
int ard[4][2]= {{1,0},{-1,0}, {0,1}, {0,-1}};//分别代表四个可走的方向
int w,h;
int cnt;
void dfs(int x,int y)//到了[x][y]这里
{
vis[x][y]=1;//标记走过啦
for(int i=0; i<4; i++)//遍历[x][y]的四个方向
{
int a=x+ard[i][0];
int b=y+ard[i][1];
if(way[a][b]=='.'&&!vis[a][b]&&a<h&&a>=0&&b<w&&b>=0)//可以走
{
cnt++;
dfs(a,b);
}
}
}
int main()
{
while(cin>>w>>h&&w!=0&&h!=0)
{
cnt=0;
memset(way,0,sizeof(way));
memset(vis,0,sizeof(vis));//清空数组,cnt归零
for(int i=0; i<h; i++)
cin>>way[i];
for(int i=0; i<h; i++)
{
for(int j=0; j<w; j++)
{
if(way[i][j]=='@')//遇起点
dfs(i,j);//开始遍历
}
}
cout<<cnt+1<<endl;//走过的再加上起点
}
return 0;
}
BFS
#include<cstdio>
#include<queue>
#include<iostream>
using namespace std;
char way[30][30];
bool vis[30][30]={0};
int x,y,sum;
int dir[4][2]={1,0,0,1,-1,0,0,-1};
struct node
{
int x,y;
}q[500];
void BFS(int x0,int y0)
{
queue<node>q;
node re,pre;
re.x=x0;
re.y=y0;
q.push(re);
while(!q.empty())
{
re=q.front();
q.pop();
for(int i=0;i<4;i++)
{
pre.x=re.x+dir[i][0];
pre.y=re.y+dir[i][1];
if(!vis[a][b]&&a<h&&a>=0&&b<w&&b>=0&&way[pre.x][pre.y]=='.')
{
vis[pre.x][pre.y]=1;
sum++;
q.push(pre);
}
}
}
}
int main()
{
int i,j,di,dj;
while (scanf("%d%d",&x,&y)!=EOF)
{
getchar();
if (x==0&&y==0) break;
for (i=0; i<y; i++)
{
for (j=0; j<x; j++)
{
scanf("%c",&way[i][j]);
if(way[i][j] == '@')
{
di = i;
dj = j;
}
}
getchar();
}
sum=1;
BFS(di,dj);
printf("%d\n",sum);
}
return 0;
}