【模板】启发式搜索

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int maxn=1e2+50,INF=0x3f3f3f3f;
int dx[6]={0,0,-1,0,1},dy[6]={0,-1,0,1,0},n,m,k,sx,sy,ex,ey,a[maxn][maxn],f[maxn],g[maxn][maxn],vis[maxn][maxn];
struct Node{
	int x,y,fx;
	Node(){}
	Node(int a,int b,int c){
		x=a;y=b;fx=c;
	}
	friend bool operator <(const Node &A,const Node &B){
		return A.fx>B.fx;
	}
};
inline int read(){
	int s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){
		if(ch=='-')w=-1;ch=getchar();
	}
	while(ch>='0'&&ch<='9')s=s*10+ch-'0',ch=getchar();
	return s*w;
}
int dis(int x,int y){
	return abs(x-ex)+abs(y-ey);
}
void Astar(){
	memset(g,0x3f,sizeof(g));
	g[sx][sy]=0;
	priority_queue<Node> q;
	q.push(Node(sx,sy,0));
	while(!q.empty()){
		Node now=q.top();q.pop();vis[now.x][now.y]=1;
		for(int i=1;i<=4;i++){
			int x=now.x+dx[i],y=now.y+dy[i];
			if(x<1||y<1||x>m||y>n||vis[x][y]==1||a[x][y]==1)continue;
			if(g[x][y]>g[now.x][now.y]+1)g[x][y]=g[now.x][now.y]+1;
			else continue;
			if(x==ex&&y==ey){
				cout<<g[x][y]<<endl;
				return;
			}
		//	cout<<g[x][y]<<endl;
			q.push(Node(x,y,g[x][y]+dis(x,y)));
		}
	}
}
int main(){
	freopen("a.in","r",stdin);
	m=read(),n=read(),k=read();
	sx=read(),sy=read(),ex=read(),ey=read();
	for(int i=1;i<=k;i++){
		int x=read(),y=read();
		a[x][y]=1;
	}
	Astar();
}

猜你喜欢

转载自www.cnblogs.com/614685877--aakennes/p/12907329.html