输入样例
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
0 0
该题用bfs实现我第一次用递归实现的bfs实现
代码如下
#include<iostream>
#include<cstring>
using namespace std;
const int N=22;
long long sum;
char mp[N][N];
int book[N][N];
int net[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int sx,sy;
int w,h;
void fd()
{
for(int i=1;i<=h;i++)
for(int j=1;j<=w;j++)
if(mp[i][j]=='@')
{
sx=i;sy=j;
}
return;
}
void bfs1(int a,int b)
{
book[a][b]=1;sum++;
for(int i=0;i<=3;i++)
{
int tx=a+net[i][0];
int ty=b+net[i][1];
// cout<<a<<" "<<b<<endl;
if(tx<1||ty<1||tx>h||ty>w)
continue;
if(book[tx][ty]==0&&mp[tx][ty]=='.')
bfs1(tx,ty);
}
return;
}
int main(void)
{
while(cin>>w>>h)
{
if(w==0&&h==0)
break;
for(int i=1;i<=h;i++)
scanf("%s",mp[i]+1);
sum=0;
// for(int i=1;i<=N;i++)
// for(int j=1;j<=N;j++)
// book[i][j]=0;
memset(book,0,sizeof(book));
fd();
// cout<<sx<<" "<<sy<<endl;;
// for(int i=1;i<=h;i++)
// printf("%s\n",mp[i]+1);
bfs1(sx,sy);
cout<<sum<<endl;
}
}
由于有很多库函数还不会用,所以debug比较多。
然后这是老师的视频讲解,老师把这个叫做flood fiil(洪水灌溉)分为两种dfs、bfs,老师的代码(自己手写,用queue实现。
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
//#define x1 first;
//#define y1 second;
typedef pair<int,int> pll;
const int N=25;
int n,m,sx,sy;
char g[N][N];
int bfs(int ex,int ey)
{
int sum=1;
pll lc;
lc.first=ex;lc.second=ey;
queue<pll> p;
p.push(lc);
g[ex][ey]='$';
while(p.size())
{
auto t=p.front();
p.pop();
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
for(int k=0;k<4;k++)
{
int tx=t.first+dx[k];
int ty=t.second+dy[k];
if(tx<0||ty<0||ty>m||tx>n||g[tx][ty]!='.')
continue;
lc.first=tx;lc.second=ty;
p.push(lc);g[tx][ty]='&';
sum++;
}
}
return sum;
}
int main(void)
{
while(cin>>m>>n,m||n)
{
for(int i=0;i<n;i++)
cin>>g[i];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(g[i][j]=='@')
{sx=i;sy=j;}
cout<<bfs(sx,sy)<<endl;
}
}
还应多看看queue,pair相关知识。
然后我发现一个很好玩的现象
前两个是queue方式实现,第三个是递归实现。
老师说他不喜欢万能头的原因是因为运行时间会很长,可能用queue文件增加了运行时间。