計蒜客 蒜頭君回家 BFS

#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
int n,m;
char Map[2010][2010];
bool inq1[2010][2010] = {false};
bool inq2[2010][2010] = {false};
int X[4] = {0,0,-1,1};
int Y[4] = {1,-1,0,0};
struct node{
	int x,y,step = 0;
	bool key;
}Node;
int BFS1(int x,int y){//從(x,y)抵達P的最短路徑 
	queue<node> q;
	Node.x = x;
	Node.y = y;
	Node.step = 0;
	Node.key = false;
	inq1[Node.x][Node.y] = true;
	q.push(Node);
	while(!q.empty()){
		node top = q.front();
		q.pop();
		for(int i =0;i<4;i++){
			Node.x = top.x + X[i];
			Node.y = top.y + Y[i]; 
			if(Node.x>=0&&Node.x<n&&Node.y>=0&&Node.y<m&&Map[Node.x][Node.y]!='#'&&((top.key&&inq2[Node.x][Node.y]==false)||inq1[Node.x][Node.y]==false)){
				Node.step = top.step + 1;
				Node.key = top.key;
				if(Map[Node.x][Node.y] =='P'||top.key){
					Node.key = true;
					inq2[Node.x][Node.y] = true;
				}
				if(Map[Node.x][Node.y] =='T'&&Node.key){
					return Node.step;
				}
				q.push(Node);
				//cout<<Node.x<<" "<<Node.y<<" "<<Map[Node.x][Node.y]<<" "<<Node.step<<'\n';
				inq1[Node.x][Node.y] = true;	
				}
		}
	}
	return 0;
}
int main(){
	//freopen("in.txt","r",stdin);
	cin>>n>>m;
	int sx;
	int sy;
	for(int i = 0;i<n;i++){
		for(int j =0;j<m;j++){
			cin>>Map[i][j];
			if(Map[i][j]=='S'){
				sx = i;
				sy = j; 
			}
		}
	}
	cout<<BFS1(sx,sy)<<'\n';
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章