http://poj.org/problem?id=3083
从S到E,分别求靠左边,右边和最短距离到达出口所需步数。
dfs求靠左走的步数,方向数组按照左(0)上(1)右(2)下(3)。
注意:①当前方向的左方向 d=(d+3)%4
比如当前是右(2),此时的左方向是上(1)。
②求起点到终点 的靠右走,即从终点向起点的靠左走。
然后BFS求最短路.
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=50;
int T,n,m;
int sx,sy,ex,ey;
char G[maxn][maxn];
bool vis[maxn][maxn];
int cnt;
bool flag;
int dir[4][2]={0,-1,-1,0,0,1,1,0};
struct Node{
int x,y;
int dis;
};
void dfs(int x,int y,int tx,int ty,int d){
if (x==tx&&y==ty){
flag=true;
cout << cnt << " ";
return;
}
d=(d+3)%4; //重点,当前方向的左方向
for (int i=d;i<d+4;i++){
int xx=x+dir[i%4][0];
int yy=y+dir[i%4][1];
if (xx>=0&&xx<n&&yy>=0&&yy<m&&G[xx][yy]!='#'){
cnt++;
dfs(xx,yy,tx,ty,i);
if (flag){
return;
}
}
}
}
void bfs(){
queue <Node> q;
Node now;
now.x=sx;
now.y=sy;
now.dis=1;
q.push(now);
while (!q.empty()){
now=q.front();
if (now.x==ex&&now.y==ey){
cout << now.dis << endl;
return;
}
q.pop();
for (int i=0;i<4;i++){
Node temp;
temp.x=now.x+dir[i][0];
temp.y=now.y+dir[i][1];
temp.dis=now.dis+1;
if (temp.x>=0&&temp.x<n&&temp.y>=0&&temp.y<m&&!vis[temp.x][temp.y]&&G[temp.x][temp.y]!='#'){
vis[temp.x][temp.y]=true;
q.push(temp);
}
}
}
}
int main(){
cin >> T;
while (T--){
cin >> m >> n;
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
cin >> G[i][j];
if (G[i][j]=='S'){
sx=i;
sy=j;
}
if (G[i][j]=='E'){
ex=i;
ey=j;
}
}
}
flag=false;
cnt=1;
dfs(sx,sy,ex,ey,0);
flag=false;
cnt=1;
dfs(ex,ey,sx,sy,0);
flag=false;
cnt=1;
memset(vis,false,sizeof(vis));
bfs();
}
}