题目链接
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).
Sample Input
6 9
…#.
…#
…
…
…
…
…
#@…#
.#…#.
11 9
.#…
.#.#######.
.#.#…#.
.#.#.###.#.
.#.#…@#.#.
.#.#####.#.
.#…#.
.#########.
…
11 6
…#…#…#…
…#…#…#…
…#…#…###
…#…#…#@.
…#…#…#…
…#…#…#…
7 7
…#.#…
…#.#…
###.###
…@…
###.###
…#.#…
…#.#…
0 0
1深搜:通过递归方法,从图结构的一个结点开始深度搜索。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int w,h,sum;
char mp[25][25];
int ds1[4]={-1,1,0,0};
int ds2[4]={0,0,-1,1};
void dfs(int x,int y)
{
mp[x][y]='#';
sum++;
for(int i=0;i<4;i++)
{
int tx=x+ds1[i];//朝4个方向走
int ty=y+ds2[i];
if(tx>=0&&tx<h&&ty>=0&&ty<w&&mp[tx][ty]=='.')
{
dfs(tx,ty);
}
}
}
int main()
{
while(cin>>w>>h)
{
if(w==0&&h==0)
break;
sum=0;
int x,y;
for(int i=0;i<h;i++)
for(int j=0;j<w;j++)
cin>>mp[i][j];
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
if(mp[i][j]=='@')
{
x=i;
y=j;
}
}
}
dfs(x,y);
cout<<sum<<endl;
}
return 0;
}
2广搜:
#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
typedef struct
{
int x,y;
}node;
int w,h,a,b;
char c[25][25];
void sert()
{
int i,f[4][2]={0,1,0,-1,1,0,-1,0},p=0;;
queue<node> q;
node t,temp;
t.x=a;
t.y=b;
q.push(t);//将t压入队列尾部
//队列在队尾进行插入,在队头进行删除。
while(!q.empty())
{
t=q.front();//队首元素的返回值赋给t
q.pop();//删除队首元素
for(i=0;i<4;i++)
{
temp.x=t.x+f[i][0];
temp.y=t.y+f[i][1];
if(temp.x>=0&&temp.x<h&&temp.y<w&&temp.y>=0&&c[temp.x][temp.y]!='#')
{
p++;
q.push(temp);
c[temp.x][temp.y]='#';
}
}
}
printf("%d\n",p);
}
int main()
{
int i,j;
while(scanf("%d%d",&w,&h))
{
if(w==0&&h==0)
break;
for(i=0;i<h;i++)
{
getchar();
for(j=0;j<w;j++)
{
scanf("%c",&c[i][j]);
if(c[i][j]=='@')
{
a=i;
b=j;
}
}
}
sert();
}
return 0;
}