定义一个二维数组: 

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问题,求最短路径,这里要求输出最短路的路径,这里我用了一个结构体的二维数组来存放当前该点前一个结点的坐标,最后再从终点往前得到所有路线的下标,可以把这些下标放到栈里再输出,即可得到从起点到终点的下标。

代码:

#include<iostream>
#include<stack>
#include<queue>
#include<cstdio>
using namespace std;
int mp[5][5];
int vis[5][5];
typedef struct {
    int x;
    int y;
} P; 
P pre[5][5];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {-1, 1, 0, 0};
void bfs() {
    queue<P> que;
    P q;
    q.x = 0; q.y = 0;
    que.push(q);
    while(que.size()) {
        P p = que.front();
        que.pop();
        int x = p.x, y = p.y;
        if(x == 4 && y == 4) break; 
        for(int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if(nx >= 0 && nx < 5 && ny >= 0 && ny < 5 && !vis[nx][ny] && mp[nx][ny] == 0) {
                vis[nx][ny] = 1;
                pre[nx][ny].x = x;
                pre[nx][ny].y = y;
                P p; 
                p.x = nx; p.y = ny;
                que.push(p);
            }
        }
    }
}
int main() {
    for(int i = 0; i < 5; i++) {
        for(int j = 0; j < 5; j++) {
            scanf("%d", &mp[i][j]);
            vis[i][j] = 0;
        }
    }
    bfs();
    int x = 4, y = 4; 
    stack<P> ans;
    while(!(x == 0 && y == 0)) {
        P p;
        p.x = x; p.y = y; 
        ans.push(p);
        int a = x, b = y;
        x = pre[a][b].x;
        y = pre[a][b].y;
    }
    printf("(0, 0)\n");
    while(ans.size()) {
        P p = ans.top();
        ans.pop();
        printf("(%d, %d)\n", p.x, p.y);
    }
    return 0;
}
posted on 2018-07-11 21:41  kindleheart  阅读(523)  评论(0)    收藏  举报