UVA 11573 Ocean Currents --BFS+优先队列

时间:2023-03-14 11:06:08

采用优先队列做BFS搜索,d[][]数组记录当前点到源点的距离,每次出队时选此时eng最小的出队,能保证最先到达的是eng最小的。而且后来用普通队列试了一下,超时。。所以,能用优先队列的,就要用优先队列。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
#define N 1003 struct node
{
int x,y;
int eng;
bool operator <(const node &a)const
{
return eng>a.eng;
}
}; char ss[N][N];
int dis[N][N];
int n,m,res;
int dx[] = {-,-,,,,,,-};
int dy[] = {,,,,,-,-,-}; bool OK(int nx,int ny)
{
if(nx >= && nx <= n && ny >= && ny <= m)
return true;
return false;
} int bfs(node s,node t)
{
priority_queue<node> que;
while(!que.empty())
que.pop();
que.push(s);
dis[s.x][s.y] = ;
while(!que.empty())
{
node tmp = que.top();
que.pop();
if(tmp.x == t.x && tmp.y == t.y)
return tmp.eng;
for(int i=;i<;i++)
{
node now;
now.x = tmp.x + dx[i];
now.y = tmp.y + dy[i];
if(!OK(now.x,now.y))
continue;
if(ss[tmp.x][tmp.y] - '' != i)
now.eng = tmp.eng + ;
else
now.eng = tmp.eng;
if(dis[now.x][now.y] != - && now.eng >= dis[now.x][now.y])
continue;
dis[now.x][now.y] = now.eng;
que.push(now);
}
}
return -;
} int main()
{
int i,j,q;
node s,t;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=;i<=n;i++)
scanf("%s",ss[i]+);
scanf("%d",&q);
while(q--)
{
memset(dis,-,sizeof(dis));
scanf("%d%d%d%d",&s.x,&s.y,&t.x,&t.y);
s.eng = ;
res = bfs(s,t);
printf("%d\n",res);
}
}
return ;
}