#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<queue>
#define inf 8000
using namespace std;
int r,c;
int rs,cs,re,ce;
int step[1100][1100];
int map[1100][1100];
int dir[8][2]={-1,0,-1,1,0,1,1,1,1,0,1,-1,0,-1,-1,-1};
struct node{
int x,y;
int t;
friend bool operator <(node a,node b){
return a.t>b.t;
}//优先队列的关键,先考虑步数小的出队列
};
bool is_ok(node a){
if(a.t<step[a.x][a.y]&&a.x>=1&&a.x<<r&&a.y>=1&&a.y<=c)
return 1;
else
return 0;
}
void bfs(){
priority_queue<node> Q;
memset(step,inf,sizeof(step));
node s;
s.x=rs;
s.y=cs;
s.t=0;
step[rs][cs]=0;
Q.push(s);
while(!Q.empty()){
node h=Q.top();
Q.pop();
if(h.x==re&&h.y==ce)
return;
for(int i=0;i<8;i++){
node u;
u.x=h.x+dir[i][0];
u.y=h.y+dir[i][1];
u.t=h.t;
if(map[h.x][h.y]!=i)
u.t+=1;
if(is_ok(u)){
step[u.x][u.y]=u.t;
Q.push(u);
}
}
}
}
int main(){
while(cin>>r>>c){
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
scanf("%1d",&map[i][j]);//神奇
}
}
int n;
cin>>n;
while(n--){
cin>>rs>>cs>>re>>ce;
if(rs==re&&cs==ce)
{
cout<<0<<endl;
continue;
}
bfs();
cout<<step[re][ce]<<endl;
}
}
}
hdu 2757 优先队列
最新推荐文章于 2021-01-26 22:53:11 发布