# [USACO07OCT]障碍路线 & yzoj P1130 拐弯 题解

#include<bits/stdc++.h>
using namespace std;
int n,sx,sy,ex,ey,a[110][110];
char k;
bool book[110][110];
int ans=1<<30;
bool cheak(int x,int y){
if(x<1||y>n||y<1||x>n||a[x][y]||book[x][y]) return false;
else return true;
}
void dfs(int x,int y,int dir,int step){
if(x==ex&&y==ey){
ans=min(step,ans);
return;
}
if(step>ans) return;
if(dir){
if(cheak(x+1,y)){
book[x+1][y]=1;
dfs(x+1,y,dir,step);
book[x+1][y]=0;
}
if(cheak(x-1,y)){
book[x-1][y]=1;
dfs(x-1,y,dir,step);
book[x-1][y]=0;
}
if(cheak(x,y+1)){
book[x][y+1]=1;
dfs(x,y+1,0,step+1);
book[x][y+1]=0;
}
if(cheak(x,y-1)){
book[x][y-1]=1;
dfs(x,y-1,0,step+1);
book[x][y-1]=0;
}
}
else{
if(cheak(x+1,y)){
book[x+1][y]=1;
dfs(x+1,y,1,step+1);
book[x+1][y]=0;
}
if(cheak(x-1,y)){
book[x-1][y]=1;
dfs(x-1,y,1,step+1);
book[x-1][y]=0;
}
if(cheak(x,y+1)){
book[x][y+1]=1;
dfs(x,y+1,dir,step);
book[x][y+1]=0;
}
if(cheak(x,y-1)){
book[x][y-1]=1;
dfs(x,y-1,0,step);
book[x][y-1]=0;
}
}
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
scanf("%c",&k);
if(k=='A'){
sx=i;
sy=j;
}
else if(k=='B'){
ex=i;
ey=j;
}
else if(k=='x'){
a[i][j]=1;
}
else if(k=='.'){
a[i][j]=0;
}
else j--;
}
}
dfs(sx,sy,0,0);
dfs(sx,sy,1,0);
if(ans==1<<30) printf("-1");
else printf("%d",ans);
return 0;
}

posted @ 2019-08-27 10:00  End_donkey  阅读(127)  评论(0编辑  收藏  举报