题解
此题不难,但是很恶心。迷宫的图数据太繁琐了,比较考验细心。
做法就是单纯的BFS,判断后加步数就好。但是要走两次,然后每处取最小,最后判断即可。
Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <utility>
#include <algorithm>
using namespace std;
int n,m;
typedef pair<int,int> P;
int cot[250][80];
int step[250][80];
int step_ct[5000];
int Mx[4]={-2,0,2,0};
int My[4]={0,2,0,-2};
int exo[2][2];
void bfs(int i,int j){
queue<P> que;
que.push( P(i,j));
step[i][j] = 1;
P tmp;
int tmpx,tmpy;
while( !que.empty()){
tmp = que.front();
que.pop();
for(int k=0;k<4;k++){
tmpx = tmp.first + Mx[k]/2;
tmpy = tmp.second + My[k]/2;
if(cot[tmpx][tmpy]==1) continue;
tmpx = tmp.first + Mx[k];
tmpy = tmp.second + My[k];
if( tmpx>0 && tmpx<2*n &&
tmpy>0 && tmpy<2*m && step[tmpx][tmpy]==0 &&
cot[tmpx][tmpy]!=1) {
step[tmpx][tmpy] = step[tmp.first][tmp.second]+1;
que.push(P(tmpx,tmpy));
}
}
}
}
int main(void){
freopen("maze1.out","w",stdout);
freopen("maze1.in","r",stdin);
cin>>m>>n;
string str;
getchar();// 神烦
for(int i=0;i<2*n+1;i++){
getline(cin,str);
for(int j=0;j<2*m+1;j++){
if(str[j]=='-'||str[j]=='+'||str[j]=='|') cot[i][j] = 1;
}
}
int t=0,ex; // exo 出口
for(int i=0;i<=2*n;i+=2*n)
for(int j=0;j<2*m+1;j++)
if(cot[i][j] == 0){
if(i==0) ex=1;// 用ex处理一下 使得计算时候在迷宫内
else ex=-1;
exo[t][0]=i+ex;
exo[t++][1]=j;
}
for(int j=0;j<=2*m;j+=2*m)
for(int i=0;i<2*n+1;i++)
if(cot[i][j] == 0){
if(j==0) ex=1;
else ex=-1;
exo[t][0]=i;
exo[t++][1]=j+ex;
}
bfs(exo[0][0],exo[0][1]);// 第一次
int k=0;
for(int i=0;i<2*n+1;i++)
for(int j=0;j<2*m+1;j++){
if(step[i][j]!=0) step_ct[k++]=step[i][j];// 步数记录集合
}
memset(step,0,sizeof(step));
bfs(exo[1][0],exo[1][1]);// 第二次
k=0;
for(int i=0;i<2*n+1;i++)
for(int j=0;j<2*m+1;j++){
if(step[i][j]!=0) {
step_ct[k]=min(step_ct[k],step[i][j]);// 步数记录集合 更新
k++;
}
}
int ans = 0;
for(int i=0;i<k;i++){
ans = max(step_ct[i],ans);
}
cout<<ans<<endl;
return 0;
}