您的位置:首页 > 其它

UVa 10285 BFS的做法

2016-07-27 10:39 267 查看
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>

using namespace std;

const int maxn=300;
int t,r,c;
char a[maxn];
int vis[maxn][maxn],m[maxn][maxn];//step代表当前结点能到达的最长的长度值
//step用作存储记忆化的功能,所以不需要再每次跑循环的时候都再初始化一次,那个不同于一般的BFS,且若在BFS下循环里再钳套初始化memset那样钳套的话容易超时
int dr[4][2]={{1,0},{-1,0},{0,1},{0,-1}};

struct point
{
int x,y;
int p;
}step[maxn][maxn];

int BFS(int x,int y)
{
int mm=-1;
queue<point>q;
point t;
t.x=x;t.y=y;t.p=1;
q.push(t);
while(!q.empty())
{
point temp;
temp=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int dx=temp.x+dr[i][0];
int dy=temp.y+dr[i][1];
if(dx>=1&&dx<=r&&dy>=1&&dy<=c&&m[dx][dy]<m[temp.x][temp.y])
{
step[dx][dy].p=temp.p+1;
int ct=step[dx][dy].p;
if(ct>mm)
mm=ct;
q.push(step[dx][dy]);
}
}
}
return mm;
}

int main()
{
int maxs;
cin>>t;
while(t--)
{
maxs=-1;
cin>>a;
cin>>r>>c;
for(int i=1;i<=r;i++)
{
for(int j=1;j<=c;j++)
{
cin>>m[i][j];
step[i][j].x=i;
step[i][j].y=j;
step[i][j].p=1;
}
}
memset(vis,0,sizeof(vis));
for(int i=1;i<=r;i++)
for(int j=1;j<=c;j++)
{

int cnt=BFS(i,j);
if(cnt>maxs) maxs=cnt;
}
cout<<a<<": "<<maxs<<endl;
}
return 0;
}
其实BFS也是可以的,只不过看起来稍微略显笨拙,没有DFS看起来那么的好,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: