bfs搜索
作者:互联网
Rescue
x从r走到a,遇到.消耗一秒,遇到x消耗2秒,问最少需要多少秒
#include<stdio.h>
#include<queue>
#include<stack>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m;
char a[1010][1010];
int book[1010][1010];
int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct node
{
int x,y,step;
bool operator<(const node &a)const
{
return a.step<step;
}
};
void dfs(int x,int y)
{
memset(book,0,sizeof(book));
priority_queue<node>q;
node now,next;
now.x=x;
now.y=y;
now.step=0;
book[x][y]=1;
q.push(now);;
while(!q.empty())
{
next=q.top();
q.pop();
if(a[next.x][next.y]=='a')
{
printf("%d\n",next.step);
return;
}
for(int i=0;i<4;i++)
{
int tx=next.x+d[i][0];
int ty=next.y+d[i][1];
if(tx<0||ty<0||tx>=n||ty>=m||book[tx][ty]==1||a[tx][ty]=='#')
continue;
book[tx][ty]=1;
now.x=tx;
now.y=ty;
now.step=next.step+1;
if(a[tx][ty]=='x')
now.step++;
q.push(now);
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
return;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<n;i++)
scanf("%s",a[i]);
int x1,y1;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(a[i][j]=='r')
{
x1=i;
y1=j;
}
}
}
dfs(x1,y1);
}
return 0;
}
A计划
援救公主,S为迷宫入口,P为公主所在地点,#代表传输机,可以传送到另外一层,.代表平地,*代表墙
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m,T;
int d[4][2]={0,1,0,-1,1,0,-1,0};
int vis[15][15][15];
char a[15][15][15];
struct node
{
int x,y,z,step;
}pre,now;
int dfs()
{
queue<node>q;
now.x=now.y=now.z=1;
now.step=0;
q.push(now);
while(!q.empty())
{
pre=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int tx=pre.x+d[i][0];
int ty=pre.y+d[i][1];
int tz=pre.z;
int t=pre.step+1;
if(tx<1||ty<1||tx>n||ty>m||tz>2||vis[tx][ty][tz]||a[tx][ty][tz]=='*')
continue;
vis[tx][ty][tz]=1;
if(a[tx][ty][tz]=='#')
{
if(tz==1)
tz++;
else
tz--;
if(vis[tx][ty][tz]||a[tx][ty][tz]=='*'||a[tx][ty][tz]=='#')
continue;
vis[tx][ty][tz]=1;
}
if(a[tx][ty][tz]=='P')
{
if(t<=T)
return 1;
else
return 0;
}
now.x=tx;
now.y=ty;
now.z=tz;
now.step=t;
q.push(now);
}
}
return 0;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(vis,0,sizeof vis);
scanf("%d%d%d",&n,&m,&T);
for(int k=1;k<=2;k++)
{
if(k!=1)
getchar();
for(int i=1;i<=n;i++)
{
getchar();
for(int j=1;j<=m;j++)
scanf("%c",&a[i][j][k]);
}
}
if(dfs())
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
标签:tz,tx,ty,int,bfs,step,搜索,now 来源: https://blog.csdn.net/touso/article/details/116244045