题目:http://poj.org/problem?id=3083
AC代码(C++):
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
#include <string>
#include <string.h>
#include <bitset>
#define INF 0xfffffff
#define MAXN 45
using namespace std;
char map[MAXN][MAXN];
bool vis[MAXN][MAXN];
int r,c;
int sx, sy;
int dir[][2] = {{-1,0},{0,1},{1,0},{0,-1}};//wdsa
struct point{
int x,y,step;
};
int bfs(int x, int y) {
queue<point> q;
memset(vis, false, sizeof(vis));
point start;
start.x = x;
start.y = y;
start.step = 0;
vis[x][y] = true;
q.push(start);
point node;
while (!q.empty()) {
node = q.front();
q.pop();
if(map[node.x][node.y]=='E'){
return node.step + 1;
}
for(int i = 0; i < 4; i++){
point tmp;
tmp.x = node.x + dir[i][0];
tmp.y = node.y + dir[i][1];
if (tmp.x>=0&&tmp.y>=0&&tmp.x<r&&tmp.y<c&&map[tmp.x][tmp.y]!='#'&&vis[tmp.x][tmp.y]==false) {
tmp.step = node.step + 1;
q.push(tmp);
vis[tmp.x][tmp.y] = true;
}
}
}
return -1;
}
int left(int x, int y){
int step = 0;
int dir0;//0123wdsa
if(x==0)dir0 = 2;
else if(x==r-1)dir0 = 0;
else if(y==0)dir0 = 1;
else if(y==c-1)dir0 = 3;
while(1){
if(map[x][y]=='E')break;
int tmpx,tmpy;
for(int i = 0; i < 4; i++){
int dir1 = (dir0 + 3 + i)%4;
tmpx = x + dir[dir1][0];
tmpy = y + dir[dir1][1];
if(tmpx>=0&&tmpy>=0&&tmpx<r&&tmpy<c&&map[tmpx][tmpy]!='#'){
dir0 = dir1;
break;
}
}
x = tmpx;
y = tmpy;
step++;
}
return step + 1;
}
int right(int x, int y){
int step = 0;
int dir0;//0123wdsa
if(x==0)dir0 = 2;
else if(x==r-1)dir0 = 0;
else if(y==0)dir0 = 1;
else if(y==c-1)dir0 = 3;
while(1){
if(map[x][y]=='E')break;
int tmpx,tmpy;
for(int i = 0; i < 4; i++){
int dir1 = (dir0 + 5 - i)%4;
tmpx = x + dir[dir1][0];
tmpy = y + dir[dir1][1];
if(tmpx>=0&&tmpy>=0&&tmpx<r&&tmpy<c&&map[tmpx][tmpy]!='#'){
dir0 = dir1;
break;
}
}
x = tmpx;
y = tmpy;
step++;
}
return step + 1;
}
int main()
{
int t;
cin>>t;
while(t--){
cin>>c>>r;
for(int i = 0; i < r; i++)cin>>map[i];
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
if(map[i][j]=='S'){
sx = i;
sy = j;
break;
}
}
}
cout<<left(sx,sy)<<' '<<right(sx,sy)<<' '<<bfs(sx,sy)<<endl;
}
}
总结: 题意是要我们分别用三种方法走迷宫并记录距离. 最短距离不用说了, 最左的思路是: 记录每次前进的方向, 本次前进的方向就是从上次前进方向的左边开始顺时针找. 最右同理, 就是从上次前进方向的右边开始逆时针找. 这题TLE了一次, 因为第一次找最短路用的是dfs, 换了bfs就搞定了.