POJ 3984 迷宫问题
生活随笔
收集整理的這篇文章主要介紹了
POJ 3984 迷宫问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
定義一個二維數組:
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)
解題思路:
用一個二維數組記錄路徑。
代碼如下:
#include <iostream> #include <queue> #include <cstdio> using namespace std; const int N = 110; char g[N][N]; bool vis[N][N];int dx[] = {0, 0, 1, -1};int dy[] = {1, -1, 0, 0};struct node {int x, y;int step;int path[105][3]; };void bfs() {queue<node>q;int sx = 0, sy = 0;int ex = 4, ey = 4;node start;start.x = sx;start.y = sy;start.step = 0;start.path[0][0] = sx;start.path[0][1] = sy;vis[0][0] = true;q.push(start);while (q.size()) {node t = q.front();q.pop();if (t.x == ex && t.y == ey) {for (int i = 0; i < t.step; i++) {printf("(%d, %d)\n", t.path[i][0], t.path[i][1]);}cout << "(4, 4)" << endl;}for (int i = 0; i < 4; i++) {int xx = t.x + dx[i];int yy = t.y + dy[i];if (xx < 0 || xx > 4 || yy < 0 || yy > 4)continue;if (vis[xx][yy] || g[xx][yy] == '1')continue;node next;next = t;next.x = xx;next.y = yy;next.step = t.step + 1;next.path[next.step][0] = xx;next.path[next.step][1] = yy;vis[xx][yy] = true;q.push(next);}} }int main() {for (int i = 0; i < 5; i++)for (int j = 0; j < 5; j++)cin >> g[i][j];bfs();return 0; }總結
以上是生活随笔為你收集整理的POJ 3984 迷宫问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高等数学上-赵立军-北京大学出版社-题解
- 下一篇: Oray什么是别名