计蒜客 走迷宫2 BFS

#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 110;
struct node{
	int x,y;
	int deep;
}Node;
int X[4] = {0,0,1,-1};
int Y[4] = {1,-1,0,0};
int n,m;
int ans = -1;
char matrix[maxn][maxn];
bool inq[maxn][maxn] = {false};//记录是否已入队
bool judge(int x,int y){
	if(x>=n||x<0||y>=m||y<0){
		return false;
	}
	if(matrix[x][y] =='#'||inq[x][y] == true){
		return false;
	}
	return true;
}
void BFS(int x,int y){
	queue<node> q;//定义队列
	Node.x = x;
	Node.y = y;
	Node.deep = 0;
	q.push(Node);
	inq[x][y] = true;
	while(!q.empty()){
		node top = q.front();
		if(matrix[top.x][top.y] == 'T'){
			ans = top.deep;
			break;
		}
		q.pop();
		for(int i = 0;i<4;i++){
			Node.x = top.x+ X[i];
			Node.y = top.y+ Y[i];
			Node.deep = top.deep +1;
			if(judge(Node.x,Node.y))
			{
				q.push(Node);	
				inq[Node.x][Node.y] = true;
			}
		}
	}
} 
int main(){
	//freopen("in.txt","r",stdin);
	scanf("%d%d",&n,&m);
	int sx,sy;
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++)
		{
			cin>>matrix[i][j];	
			if(matrix[i][j]=='S'){
				sx = i;
				sy = j;
			}
		}
	} 
	inq[sx][sy] = true;
	BFS(sx,sy);
	if(ans>=0){
		printf("%d\n",ans);
	}
	else{
		cout<<-1<<'\n';
	}
	return 0;
}  

你可能感兴趣的:(搜索问题,计蒜客)