UVA 929 Number Maze 优先队列-BFS

题目描述
模板题,带有优先队列的BFS

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int const MAXN=1000;

struct Node{
	int x,y;
	long long d;
	Node():x(),y(),d(){}
	Node(int x,int y,int d):x(x),y(y),d(d){}
	bool operator<(const Node &x)const{
		return x.d<d;
	}
	
};

priority_queue<Node> pq;
bool visited[MAXN][MAXN];
int a[MAXN][MAXN],T,N,M,ans,dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};

bool checkXY(int x,int y){
	if(x>=1&&x<=N&&y>=1&&y<=M) return true;
	else return false;
}
void bfs(Node v){
	visited[v.x][v.y]=true;
	pq.push(v);
	while(!pq.empty()){
		Node t=pq.top();
		pq.pop();
		
		if(t.x==N&&t.y==M) {
			ans=t.d;
			break;
		}
		for(int i=0;i<4;i++){
			int tx=t.x+dx[i];
			int ty=t.y+dy[i];
			if(checkXY(tx,ty) && !visited[tx][ty]){
				visited[tx][ty]=true;
				pq.push(Node(tx,ty,t.d+a[tx][ty]));
			}
		}
		
	}
}
int main(){
	cin>>T;
	while(T--){
		cin>>N>>M;
		memset(visited,0,sizeof(visited));
		while(!pq.empty()) pq.pop();
		for(int i=1;i<=N;i++)
			for(int j=1;j<=M;j++)
				cin>>a[i][j];
				
		bfs(Node(1,1,a[1][1]));
		cout<<ans<<endl;
	}
	return 0;
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值