小组学习——迷迷宫MLE20分求助

#include <bits/stdc++.h>
using namespace std;
const int MAXN=26;
int n,a[MAXN][MAXN],tx,ty,fx,fy,ans=0,small_step=1e9+7;
int direct[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
queue<int> q;
int check(int nx,int ny){
	if (nx>=1&&nx<=n&&ny>=1&&ny<=n&&a[nx][ny]!=-1){
		return 1;
	}
	return 0;
}
void bfs(){
	q.push(tx);
	q.push(ty);
	q.push(0);
	while (!q.empty()){
		int x=q.front();
		q.pop();
		int y=q.front();
		q.pop();
		int step=q.front();
		q.pop();
		if (x==fx&&y==fy){
			small_step=step;
			ans++;
		}
		if (small_step<step){
			continue;
		}
		for(int i=0;i<4;++i){
			int nx=x+direct[i][0];
			int ny=y+direct[i][1];
			if (check(nx,ny)==1){
				a[nx][ny]=step+1;
				q.push(nx);
				q.push(ny);
				q.push(step+1);
			}
		}
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;++i){
		for(int j=1;j<=n;++j){
			char ch;
			cin>>ch;
			if (ch=='E'){
				fx=i;
				fy=j;
			}
			else if (ch=='S'){
				tx=i;
				ty=j;
			}
			else if (ch=='X'){
				a[i][j]=-1;
			}
		}
	}
	bfs();
	printf("%d\n%d",small_step,ans);
	return 0;
}

4 个赞