您的位置:首页 > 其它

算法提高 学霸的迷宫

2017-04-06 19:20 423 查看


经典的BFS问题。刚开始把vis[0][0]状态设置成了1导致dfs溢出。

/*
迷宫bfs求解,SPFA,和迷宫问题考虑用上队列操作
*/
#include<iostream>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
#define MAX 505
char map[MAX][MAX];//构造迷宫
int vis[MAX][MAX];//判断点的位置状态
int n, m;
int xx[] = { 1,0,0,-1 };//下上
int yy[] = { 0,1,-1,0 };//右左
struct node {
int x;
int y;//坐标
int t;//步数
};
struct father {
int x;
int y;//父节点
char c;//判断上下左右状态
};
node s, f;//f为末状态
father lj[MAX][MAX];
int bfs() {
queue<node>Q;
s.x = 0;
s.y = 0;
s.t = 0;
f.x = n - 1;
f.y = m - 1;
lj[s.x][s.y].x = 1000;//节点开始处的前驱设置为无穷大
lj[s.x][s.y].y = 1000;
lj[s.x][s.y].y = 0;
Q.push(s);//s进队列
while (!Q.empty()) {//队列不为空,循环操作
node p;
p = Q.front();
Q.pop();
for (int i = 0; i<4; i++) {
node pp;
pp.x = p.x + xx[i];//纵坐标
pp.y = p.y + yy[i];//横坐标
pp.t = p.t + 1;
if (pp.x >= n || pp.x<0 || pp.y >= m || pp.y<0 || vis[pp.x][pp.y] == 1 || map[pp.x][pp.y] == '1') continue;
Q.push(pp);
lj[pp.x][pp.y].x = p.x;
lj[pp.x][pp.y].y = p.y;//连接起来
if (i == 0) lj[pp.x][pp.y].c = 'D';//下
else if (i == 1) lj[pp.x][pp.y].c = 'R';
else if (i == 2) lj[pp.x][pp.y].c = 'L';
else if (i == 3) lj[pp.x][pp.y].c = 'U';
if (pp.x == f.x && pp.y == f.y) return pp.t;
}
}
return -1;
}
void dfs(int x, int y) {
if (x == 0 && y == 0) return;
dfs(lj[x][y].x, lj[x][y].y);
cout << lj[x][y].c;
}
int main(void) {
int i, j;
cin >> n >> m;
for (i = 0; i<n; i++) {
scanf("%s", map[i]);
}
memset(vis, 0, sizeof(vis));
int ans;
ans = bfs();
cout << ans << endl;
dfs(n - 1, m - 1);//回溯输出方向
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  蓝桥杯