初学A* 90pts求调

P1746 离开中山路

_lingrui @ 2023-12-11 17:04:11


#include <bits/stdc++.h>
using namespace std;
int n,sx,sy,ex,ey;
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
bool vis[1005][1005];
struct node{
    int now,f,wx,wy;
};
bool operator<(const node &a,const node &b){
    return a.f>b.f;
}
char mp[1005][1005];
priority_queue<node> q;
int fd(int x,int y){
    return abs(x-ex)+abs(y-ey);
}
int main(){
    cin >> n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin >> mp[i][j];
        }   
    }
    cin >> sx >> sy >> ex >> ey;
    q.push(node{0,fd(sx,sy),sx,sy});
    vis[sx][sy]=1;
    while(!q.empty()){
        node tmp=q.top();
        q.pop();
        for(int i=0;i<4;i++){
            int xx=tmp.wx+dx[i],yy=tmp.wy+dy[i];
            if(xx<=n&&xx>=1&&yy<=n&&yy>=1&&mp[xx][yy]=='0'&&vis[xx][yy]==0){
                q.push(node{tmp.now+1,tmp.now+1+fd(xx,yy),xx,yy});
                vis[xx][yy]=1;
                if(xx==ex&&yy==ey){
                    cout << tmp.now+1;
                    return 0;
                }
            }
        }
    }
    return 0;
}

|