迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10105 | Accepted: 6007 |
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 + 优先队列求最短路径, 用栈记录路径即可。
注意:path[0][0]默认的下标是结构体的0节点。
<pre name="code" class="cpp">#include <cstdio> #include <cstring> #include <stack> #include <queue> #include <algorithm> using namespace std; struct Node { int x, y, step, prex, prey; friend bool operator < (Node a, Node b) { return a.step > b.step; } }; Node path[5][5];//记录第一次到坐标x, y 的节点 int map[5][5];//图 int vis[5][5];//该点是否查询过 int move[4][2] = {0,1, 0,-1, 1,0, -1,0}; bool judge(int x, int y) { return x >= 0 && x < 5 && y >= 0 && y < 5 && !map[x][y] && !vis[x][y]; } void findpath(int ex, int ey) { stack<Node> rec;//用栈记录 Node now; now = path[ex][ey];//从最后节点开始 向前找 rec.push(now); while(1) { now = path[now.prex][now.prey]; rec.push(now); if(now.x == 0 && now.y == 0) break; } while(!rec.empty()) { now = rec.top(); rec.pop(); printf("(%d, %d)\n", now.x, now.y); } } void BFS() { priority_queue<Node> Q; Node now, next; now.x = 0; now.y = 0; now.step = 0; Q.push(now); vis[now.x][now.y] = true; while(!Q.empty()) { now = Q.top(); Q.pop(); if(now.x == 4 && now.y == 4) { path[now.x][now.y] = now;//记录 break; } for(int k = 0; k < 4; k++) { next.x = now.x + move[k][0]; next.y = now.y + move[k][1]; next.step = now.step + 1; if(judge(next.x, next.y)) { vis[next.x][next.y] = 1; next.prex = now.x;//记录前一路径 next.prey = now.y; Q.push(next); path[next.x][next.y] = next;//记录节点 } } } findpath(4, 4); } int main() { for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) scanf("%d", &map[i][j]); } memset(vis, 0, sizeof(vis)); BFS(); return 0; }