您的位置:首页 > 其它

poj 3083 Children of the Candy Corn 搜索

2012-07-04 02:54 369 查看
题意:有一迷宫,求从入口到出口的最短路、左优先最短路、右优先最短路。

算法:bfs+dfs

View Code

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 50;
bool vis[maxn][maxn];
char map[maxn][maxn];

int ldir[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };
int rdir[4][2] = { {-1,0},{0,-1},{1,0},{0,1} };
int n , m;
int ex , ey;

struct Node{
int x , y , step;
}S;

bool inMap(int x , int y) {
return x>=0 && x<n && y>=0 && y<m;
}

int bfs() {
queue<Node> Q;
Node tmp;
memset(vis,0,sizeof(vis));
Q.push(S);
vis[S.x][S.y] = true;
while(!Q.empty()) {
tmp = Q.front(); Q.pop();
if(map[tmp.x][tmp.y] == 'E') return tmp.step;
for(int i=0;i<4;i++) {
int x = tmp.x + ldir[i][0];
int y = tmp.y + ldir[i][1];
if(inMap(x , y)) {
if(map[x][y] != '#' && !vis[x][y]) {
Node _node;
_node.x = x;
_node.y = y;
_node.step = tmp.step + 1;
vis[x][y] = true;
Q.push(_node);
}
}
}
}
return 0;
}

int dfs(int r, int c, int d, int dir[][2]) {
int _row , _col , _d , _step;
if(map[r][c] == 'E') return 1;
for(int i=0;i<4;i++) {
_d = (d + i + 3) % 4;
_row = r + dir[_d][0];
_col = c + dir[_d][1];
if(inMap(_row , _col) && map[_row][_col] != '#') break;
}
_step = dfs(_row , _col , _d%4 , dir) + 1;
return _step;
}

int Init(int &ld , int &rd) {
if(S.x == 0) ld = rd = 1;
else if(S.x == n-1) ld = rd = 3;
else if(S.y == m-1) ld = 0 , rd = 1;
else if(S.y == 0) ld = 2 , rd = 3;
}

int main() {
int T;
scanf("%d",&T);
while(T--) {
scanf("%d%d",&m,&n);
for(int i=0;i<n;i++) {
scanf("%s",map[i]);
for(int j=0;j<m;j++) {
if(map[i][j] == 'S') {
S.x = i;
S.y = j;
S.step = 1;
}
if(map[i][j] == 'E') {
ex = i;
ey = j;
}
}
}
int ld ,rd;
Init(ld , rd);
int ans1 = dfs(S.x , S.y , ld , ldir);
int ans2 = dfs(S.x , S.y , rd , rdir);
int ans3 = bfs();
printf("%d %d %d\n",ans1,ans2,ans3);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: