题目链接:http://poj.org/problem?id=1979
本题可以用bfs和dfs,第一个是bfs,要注意控制越界问题,这道题没有终点,因此只要覆盖整个地图就可以,所以dfs和bfs都可以,bfs我采用了两个数组,一个数组用来记录地图,一个数组用来标记,而且还要注意输入时用scanf会读入回车,因此选择cin读入,就没有这种情况.dfs就是按照正常步骤进行但这道题似乎DFS更加简单,只要控制退出条件就可以。
BFS
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int dx[4] = {1,0,-1,0};
const int dy[4] = {0,1,0,-1};
const int maxn = 30;
bool vis[maxn][maxn];
bool vist[maxn][maxn];
char mp[maxn][maxn];
struct node
{
int x,y;
};
node New,now;
node s;
int t;
int w,h;
queue<node> q;
void bfs()
{
q.push(s);
vis[s.x][s.y]=true;
t=1;
while(!q.empty())
{
now=q.front();
q.pop();
//t++放在循环内外都一样,因为弹出和入队都一样。起点也是黑格子。所以要计数
for(int i=0; i<4; i++)
{
New.x = now.x+dx[i];
New.y = now.y+dy[i];
if(vist[New.x][New.y]&&!vis[New.x][New.y]&&New.x>0&&New.y>0&&New.x<=h&&New.y<=w)
{
q.push(New);
vis[New.x][New.y]=true;
t++;
}
}
}
cout<<t<<endl;
}
int main()
{
while(scanf("%d%d",&w,&h),w&&h)
{
t=0;
memset(vis,false,sizeof(vis));
memset(vist,false,sizeof(vist));
for(int i=1; i<=h;i++)
{
for(int j=1;j<=w;j++)
{
cin>>mp[i][j];
}
}
for(int i=1; i<=h; i++)
{
for(int j=1; j<=w; j++)
{
if(mp[i][j]=='@')
{
s.x=i;
s.y=j;
}
if(mp[i][j]=='.')
vist[i][j]=true;
}
}
bfs();
}
return 0;
DFS
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=30;
char mp[maxn][maxn];
bool vis[maxn][maxn];
int step;
int h,w;
void dfs(int x,int y)
{
if(x<=0||x>h)
return;
if(y<=0||y>w)
return;
if(mp[x][y]=='#'||vis[x][y])
return;
vis[x][y]=true;
step++;
dfs(x+1,y);
dfs(x-1,y);
dfs(x,y+1);
dfs(x,y-1);
}
int main()
{
int x,y;
while(cin>>w>>h,w&&h)
{
memset(vis,false,sizeof(vis));
memset(mp,'#',sizeof(mp));
for(int i=1; i<=h; i++)
{
for(int j=1; j<=w; j++)
{
cin>>mp[i][j];
}
}
for(int i=1; i<=h; i++)
{
for(int j=1; j<=w; j++)
{
if(mp[i][j]=='@')
{
x = i;
y = j;
}
}
}
step = 0;
dfs(x,y);
cout << step << endl;
}
return 0;
}