1. 程式人生 > >1726 優先佇列bfs

1726 優先佇列bfs

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<queue> 
using namespace std;
int sx,sy,n,m;
const int maxn = 105;
struct node{
	int x,y,step;
	friend bool operator<(node a,node b){
		return a.step>b.step;
	}
}now,temp,nextt;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
char s[maxn][maxn];
int vis[maxn][maxn];
void bfs(){
	memset(vis,0,sizeof(vis));
	priority_queue<node>q;
	while(!q.empty()) q.pop();
	now.x=sx,now.y=sy;
	vis[sx][sy]=1;
	now.step=0;
	q.push(now);
	while(!q.empty()){
		temp=q.top();
		q.pop();
		if(temp.x<=0||temp.x>=n-1||temp.y<=0||temp.y>=m-1){
			cout<<temp.step<<endl;
			return ;
		}
		for(int i=0;i<4;i++){
			nextt.x=temp.x+dx[i];
			nextt.y=temp.y+dy[i];
			if(!vis[nextt.x][nextt.y]&&s[nextt.x][nextt.y]!='#'){
				if(s[nextt.x][nextt.y]=='.'){
					nextt.step=temp.step;
				}
				else if(s[nextt.x][nextt.y]=='*'){
					nextt.step=temp.step+1;
				}
				vis[nextt.x][nextt.y]=1;
				q.push(nextt);	
			}
		}
	}
	cout<<"-1"<<endl;
	return ;
}
int main(){
	int T;
	cin>>T;
	while(T--){
		cin>>n>>m;
		for(int i=0;i<n;i++){
			cin>>s[i];
		}
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				if(s[i][j]=='@'){
					sx=i,sy=j;
					bfs();
				}
			}
		}
	}
	return 0;
}