您的位置:首页 > 其它

迷宫bfs:3状态+优先队列

2018-03-11 18:16 309 查看
#include <cstdio>
#include <queue>
#include <vector>
#include <functional>
using namespace std;
const int MAXN = 100+10;

typedef struct point
{
int x;
int y;
int step;
int inc;
int type;

friend bool operator < (point a,point b)
{
return a.step>b.step;
}

}point;

char  mp[MAXN][MAXN];
int n,m;
int smove[3];
priority_queue<point > q;
int dir[4][2]={-1,0,0,1,1,0,0,-1};
int vis[MAXN][MAXN][20];
int ans;

void bfs(point s)
{

s.inc=1;
s.step=0;
s.type=1;
q.push(s);
vis[s.x][s.y][s.type]=1;
while(q.size())
{
point tmb=q.top();
q.pop();
if(mp[tmb.x][tmb.y]=='4')
{
ans=tmb.step;
break;
}
for(int i=0;i<4;i++)
{
point tp;
if(tmb.type!=15)
{
tp.x=tmb.x+dir[i][0];
tp.y=tmb.y+dir[i][1];
tp.step=tmb.step+tmb.inc;
tp.type=tmb.type;
tp.inc=tmb.inc;
if(tp.x>=1&&tp.x<=n&&tp.y>=1&&tp.y<=m&&!vis[tp.x][tp.y][tp.type])
{
if(mp[tp.x][tp.y]=='.'||mp[tp.x][tp.y]=='0'||mp[tp.x][tp.y]=='#')
{
q.push(tp);
vis[tp.x][tp.y][tp.type]=1;
}
else if(mp[tp.x][tp.y]=='1'&&!(tp.type&2))
{
q.push(tp);
vis[tp.x][tp.y][tp.type]=1;
tp.type=tp.type|2;
tp.inc+=smove[0];
q.push(tp);
vis[tp.x][tp.y][tp.type]=1;
}
else if(mp[tp.x][tp.y]=='2'&&!(tp.type&4))
{
q.push(tp);
vis[tp.x][tp.y][tp.type]=1;
tp.type=tp.type|4;
tp.inc+=smove[1];
q.push(tp);
vis[tp.x][tp.y][tp.type]=1;
}
else if(mp[tp.x][tp.y]=='3'&&!(tp.type&8))
{
q.push(tp);
vis[tp.x][tp.y][tp.type]=1;
tp.type=tp.type|8;
tp.inc+=smove[2];
q.push(tp);
vis[tp.x][tp.y][tp.type]=1;
}
}
}
else
{
tp.x=tmb.x+dir[i][0];
tp.y=tmb.y+dir[i][1];
tp.step=tmb.step+tmb.inc;
tp.type=tmb.type;
tp.inc=tmb.inc;
if(tp.x>=1&&tp.x<=n&&tp.y>=1&&tp.y<=m&&!vis[tp.x][tp.y][tp.type]&&mp[tp.x][tp.y]!='#')
{
q.push(tp);
vis[tp.x][tp.y][tp.type]=1;
}
}
}
}
}

int main()
{
int cnt;
scanf("%d%d",&n,&m);
point s;
getchar();
cnt=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%c",&mp[i][j]);
}
getchar();
}
for(int i=0;i<5;i++)
{
int x,y;
scanf("%d%d",&x,&y);
mp[x][y]=i+'0';
if(i==0)
{
s.x=x;
s.y=y;
}
}
scanf("%d%d%d",&smove[0],&smove[1],&smove[2]);
bfs(s);
printf("%d\n",ans);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: