您的位置:首页 > 其它

POJ 3984 迷宫问题【迷宫最短路径 bfs】

2015-08-02 15:28 429 查看

POJ 3984 迷宫问题【迷宫最短路径 bfs】

题目链接 http://poj.org/problem?id=3984

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXL = 10; // 矩阵最大宽度
char maze[MAXL][MAXL]; // 迷宫
bool vis[MAXL][MAXL]; // 访问标记
int n, m; // 迷宫的长和宽
int dirx[4] = {0, 1, 0, -1};
int diry[4] = {1, 0, -1, 0}; // 移动方向
typedef struct point{
int x, y;
}P; // 坐标
P path[MAXL*MAXL]; // 路径队列
int pre[MAXL*MAXL]; // 记录父结点
P start, goal; // 起点 终点
P current, next; // 当前坐标 下一步的坐标

void Output(){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
printf("%d\t", maze[i][j]);
}
printf("\n");
}
}

void Input(){
memset(maze, 0, sizeof(maze));
memset(vis, 0, sizeof(vis));
n = 5;
m = 5;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
scanf("%c", &maze[i][j]);
maze[i][j] -= '0';
if(j != n-1) getchar(); // 输入空格
}
getchar(); // 输入回车
}
//Output();
}

void Print(int pos){
if(pos == 0){ // 输出起点
printf("(%d, %d)\n", path[pos].x, path[pos].y);
}
else{
int pointer;
pointer = pre[pos]; // 父结点在路径中的位置
Print(pointer);
printf("(%d, %d)\n", path[pos].x, path[pos].y);
}
}

void bfs(){
start.x = 0;
start.y = 0;
goal.x = n-1;
goal.y = m-1;
int head, tail; // 队头 队尾
int x, y, xx, yy; // x,y是当前坐标 xx,yy是下一步的坐标
head = 0;
path[0].x = start.x;
path[0].y = start.y;
pre[0] = -1;
vis[start.x][start.y] = true;
tail = 1; // 起点入队
while(head < tail){ // 如果队列不为空
x = path[head].x;
y = path[head].y;
if(x == goal.x && y == goal.y){
Print(head); // 走到终点 打印最短路径
return;
}
for(int i = 0; i < 4; i++){
xx = x + dirx[i];
yy = y + diry[i];
if(xx >= 0 && xx < n && yy >= 0 && yy < m && maze[xx][yy] == 0 && !vis[xx][yy]){
vis[xx][yy] = true;
path[tail].x = xx;
path[tail].y = yy;
pre[tail] = head;
tail++; // 当前坐标入队
}
}
head++; // 四个方向都走过后元素出队
}
}

int main(){
Input();
bfs();
return 0;
}


还有一个使用queue的版本,来自网络:

http://m.blog.csdn.net/blog/yzj577/37997073
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bfs