迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11501 | Accepted: 6870 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, };
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
一个BFS的水题,适合初学数据结构的做一做。
/*************************************************************************
> File Name: 迷宫问题.cpp
> Author: Zhanghaoran0
> Mail: chiluamnxi@gmail.com
> Created Time: 2015年08月17日 星期一 16时23分14秒
************************************************************************/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int map[6][6];
int sx, sy, ex, ey;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0 ,-1, 1};
struct node{
int x;
int y;
int lastn;
}q[1000001];
bool flag[6][6];
void print(int x){
if(q[x].lastn != -1){
print(q[x].lastn);
}
printf("(%d, %d)\n", q[x].x, q[x].y);
}
void bfs(){
memset(flag, 0, sizeof(flag));
int head = 0;
int tail = 1;
q[head].x = sx;
q[head].y = sy;
q[head].lastn = -1;
while(head < tail){
for(int i = 0; i < 4; i ++){
int tempx = q[head].x + dx[i];
int tempy = q[head].y + dy[i];
if(flag[tempx][tempy] || tempx < 0 || tempx >= 5 || tempy < 0 || tempy >= 5 || map[tempx][tempy] == 1)
continue;
q[tail].x = tempx;
q[tail].y = tempy;
q[tail].lastn = head;
flag[tempx][tempy] = true;
if(tempx == ex && tempy == ey){
print(tail);
}
tail ++;
}
head ++;
}
}
int main(void){
for(int i = 0; i < 5; i ++){
for(int j = 0; j < 5; j ++){
cin >> map[i][j];
}
}
sx = 0;
sy = 0;
ex = 4;
ey = 4;
bfs();
return 0;
}