这道题我是用最短路径来求的,首先将输入转成一个数字数组,并保存出口,接着是用这个初始数组作为一个近似的临界矩阵,用Dijkstra进行最短路径的遍历。代码如下。
#include<bits/stdc++.h>
#define INF 0xfffffff
using namespace std;
struct na{
int x;
int y;
}dij[3805];
int orin[205][80],startx[5],starty[5],start[5],ans[3805],book[3805],temp[3805];
int W=0,H=0,row=0,col=0,gen=0;
void Dijkstra(int s){
int u=0,v=0,i=0,j=0,minn=0,ct=0;
for (i=0;i<gen;i++){
ans[i]=INF;
}
i=dij[s].x;
j=dij[s].y;
if ((i-2)>=1&&!orin[i-1][j]){
ans[s-W]=1;
}
if ((j-2)>=1&&!orin[i][j-1]){
ans[s-1]=1;
}
if ((i+2)<=(row-2)&&!orin[i+1][j]){
ans[s+W]=1;
}
if ((j+2)<=(col-2)&&!orin[i][j+1]){
ans[s+1]=1;
}
book[s]=1;
for(i=0;i<(gen-1);i++){
minn=INF;
for(j=0;j<gen;j++){
if (j==s){
continue;
}
if(book[j]==0&&ans[j]<minn){
minn=ans[j];
u=j;
}
}
book[u]=1;
for(v=0;v<gen;v++){
if (v==s){
continue;
}
int x= dij[v].x>dij[u].x ? dij[v].x-dij[u].x : dij[u].x-dij[v].x;
int y= dij[v].y>dij[u].y ? dij[v].y-dij[u].y : dij[u].y-dij[v].y;
if(((x==2&&y==0)||(x==0&&y==2))&&!orin[(dij[v].x+dij[u].x)/2][(dij[v].y+dij[u].y)/2]){
if(ans[v]>ans[u]+1)
ans[v]=ans[u]+1;
}
}
}
}
int main (){
freopen ("maze1.in","r",stdin);
freopen ("maze1.out","w",stdout);
cin>>W>>H;
row=2*H+1;
col=2*W+1;
gen=W*H;
char in =' ',ss[80];
int cnt=0;
cin.getline(ss,80);
for (int i=0;i<row;i++){
cin.getline(ss,80);
for (int j=0;j<col;j++){
in =ss[j];
if (in=='+'||in=='-'||in=='|'){
orin[i][j]=1;
}
else if (i==0||j==0||i==(2*H)||j==(2*W)){
startx[cnt]=i;
starty[cnt]=j;
if (i==0){
startx[cnt]++;
}
else if (j==0){
starty[cnt]++;
}
else if (i==(2*H)){
startx[cnt]--;
}
else if (j==(2*W)){
starty[cnt]--;
}
cnt++;
}
}
}
cnt=0;
for (int i=1;i<row;i+=2){
for (int j=1;j<col;j+=2){
dij[cnt].x=i;
dij[cnt++].y=j;
}
}
int k=0;
k=0,cnt=0;
for (int i=1;i<row;i+=2){
for (int j=1;j<col;j+=2){
if ((i==startx[0]&&j==starty[0])||(i==startx[1]&&j==starty[1])){
start[k++]=cnt;
}
cnt++;
}
}
if (start[0]&&!start[1]){
start[1]=start[0];
}
Dijkstra(start[0]);
k=0;
for (int i=0;i<gen;i++){
temp[i]=ans[i];
}
memset(ans,0,sizeof(ans));
memset(book,0,sizeof(book));
Dijkstra(start[1]);
for (int i=0;i<gen;i++){
if (temp[i]==INF||ans[i]==INF){
continue;
}
ans[i]= ans[i]<temp[i] ? ans[i]:temp[i];
if (ans[i]>k&&ans[i]!=INF){
k=ans[i];
}
}
cout<<(k+1)<<endl;
// printf ("TIME: %.2f",(double)clock() / CLOCKS_PER_SEC);
return 0;
}