【洛谷】P1746 离开中山路

【题目链接】https://www.luogu.com.cn/problem/P1746

【难度】普及-

【目标】网格最短路径的A*实现练习,用曼哈顿距离作为估价函数,对比普通BFS的效率差异。

 

普通bfs,用时:159ms

#include<iostream>
#include<queue> 
#include<cstring>
using namespace std;

struct Node{
    int x,y;
    int cnt; 
};

char mapp[1005][1005];
bool visit[1005][1005];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    int n;
    int sx,sy,ex,ey;
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>mapp[i][j];
        }
    }
    cin>>sx>>sy>>ex>>ey;
    Node head;
    head.cnt = 0;
    head.x = sx;
    head.y = sy;
    visit[sx][sy] = 1;
    queue<Node> que;
    que.push(head);        
    while(!que.empty()){
        Node f = que.front();
        if( f.x == ex && f.y == ey){
            cout<<f.cnt<<endl;
            break;
        }
        for(int i=0;i<4;i++){
            int tx = dx[i]+f.x;
            int ty = dy[i]+f.y;
            if( 1<=tx&&tx<=n && 1<=ty&&ty<=n && mapp[tx][ty] == '0' && !visit[tx][ty]){
                Node tmp;
                tmp.x = tx;
                tmp.y = ty;
                tmp.cnt = f.cnt+1;
                visit[tx][ty] = 1;
                que.push(tmp);
            }
        }
        que.pop();    
    }        
    return 0;
}

  

 

A*算法,用时:123ms

#include<bits/stdc++.h>
using namespace std;

int n,sx,sy,ex,ey;
char maze[1005][1005];
int dist[1005][1005];
int dx[]={0,0,1,-1},dy[]={1,-1,0,0};

int mht(int x,int y){
	return abs(x-ex)+abs(y-ey);
}

struct node{
	int x,y;
	int g;//从起点到达当前位置的真实最短路径
	int h;//从当前位置到达终点的预估距离
	int f;//总评估函数 f=g+h;
	
	node(int _x,int _y,int _g,int _h){
		x = _x;
		y = _y;
		g = _g;
		h = _h;
		f = _g+_h;
	}
	
	bool operator > ( const node& other ) const{
		if( f!=other.f ) return f > other.f;
		return h > other.h;
	}
	 	
};

int A_star(){
	memset( dist , 0x3f , sizeof dist ); 
	priority_queue< node , vector<node> , greater<node> > q;
	dist[sx][sy] = 0;
	//node tmp ( sx,sy,0,mht(sx,sy) ); q.push( tmp ); //和下方等价 
	q.emplace( sx,sy,0,mht(sx,sy) );
	while( q.size() ){
		node cur = q.top() ; q.pop();
        //cout << cur.x << ' ' << cur.y << endl;
		if( cur.x == ex && cur.y == ey ){
			return cur.g;
		}
		for(int i=0;i<4;i++){
			int tx = cur.x + dx[i] , ty = cur.y + dy[i] ;
			if( tx < 1 || tx > n || ty < 1 || ty > n ) continue;
			if( maze[tx][ty] == '1' ) continue;
			
			int tg = cur.g+1;
			if( tg >= dist[tx][ty] ) continue;
			
			dist[tx][ty] = tg;
			q.emplace( tx,ty,tg,mht(tx,ty) );
		}
	} 
	return -1;
}

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>maze[i][j];
		}
	}
    cin>>sx>>sy>>ex>>ey;
	cout << A_star();
	return 0;
}

  

posted @ 2026-09-19 09:47  费先生  阅读(16)  评论(0)    收藏  举报