您的位置:首页 > 其它

HDU1072BFS与双重优先判断

2018-01-20 17:16 141 查看
这个题其实可以不用优先队列,虽然是以用时最少为首,但是没有打怪啥的,所以最短路径即最短用时。

其次我一直在想只用一个vis来判断走没走过,对于普通的BFS来说还行,但是这个有一个重置时间的装置,一旦时间重置了,我再回到我原来不能准时到达的路线上时,说不定就能准时到达了,所以我再进行搜索时,把地图的每一个一开始搜过的点所剩时间记录了下来,我如果想要重复搜索,那么我所剩余的时间一定得比地图上记录的时间长才可以,并且这样并不会影响出队顺序,即最终的结果,只是这样能适合更多的情况了

bool is_move(int x,int y)
{
if(x >= 0 && y >= 0 && x < n && y < m && (!vis[x][y] || mp[x][y].limittime < now.limittime - 1) && mp[x][y].x != 0)
{
return true;
}
return false;
}
#include <iostream>
#include <queue>
#include <memory.h>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int foot[4][2] = {0,1,0,-1,1,0,-1,0};
int n,m,beginx,beginy,endx,endy;
int vis[10][10];
struct node{
int x;
int y;
int nowtime;
int limittime;
friend bool operator < (node a,node b)
{
return a.nowtime > b.nowtime;
}
}now,nex,mp[10][10];
priority_queue<node> q;
bool is_move(int x,int y)
{
if(x >= 0 && y >= 0 && x < n && y < m && (!vis[x][y] || mp[x][y].limittime < now.limittime - 1) && mp[x][y].x != 0)
{
return true;
}
return false;
}
bool bfs(int x,int y)
{
now.x = x;
now.y = y;
now.limittime = 6;
mp[x][y].limittime = 6;
now.nowtime = 0;
vis[x][y] = 1;
while(!q.empty())
{q.pop();}
q.push(now);
while(!q.empty())
{
now = q.top();
if(now.x == endx && now.y == endy )
{
cout<<now.nowtime<<endl;
return true;
}
q.pop();
for(int i = 0;i < 4;i++)
{

int nextx = now.x + foot[i][0];
int nexty = now.y + foot[i][1];
if(is_move(nextx,nexty))
{
if(now.limittime - 1 > 0)
{
vis[nextx][nexty] = 1;
nex.x = nextx;
nex.y = nexty;
nex.nowtime = now.nowtime + 1;
if(mp[nextx][nexty].x == 4)
{
nex.limittime = 6;
}
else
{
nex.limittime = now.limittime - 1;
}
mp[nex.x][nex.y].limittime = nex.limittime;
//cout<<nextx<<"  "<<nexty<<"  "<<nex.nowtime<<"  "<<nex.limittime<<"  "<<endl;
q.push(nex);
}
}
}
}
return false;
}
int main()
{

int t;
scanf("%d",&t);
getchar();
while(t--)
{
scanf("%d%d",&n,&m);
getchar();
memset(vis,0,sizeof(vis));
memset(mp,0,sizeof(mp));
for(int i = 0;i < n;i++)
{
for(int j = 0;j < m;j++)
{
scanf("%d",&mp[i][j].x);
if(mp[i][j].x == 2)
{
beginx = i;beginy = j;
}
if(mp[i][j].x == 3)
{
endx = i;endy = j;
}

}
getchar();
}
if(!bfs(beginx,beginy))
{
cout<<"-1"<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: