模板题,带有优先队列的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;
}