• 迷宫问题(BFS)


    定义一个二维数组: 

    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)
    ");
        while(ans.size()) {
            P p = ans.top();
            ans.pop();
            printf("(%d, %d)
    ", p.x, p.y);
        }
        return 0;
    }
    作者:kindleheart
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    HTML5 新标签
    lAMBDA表达式剖析
    whitespace 属性设置如何处理元素内的空白。
    "~/" asp.net 表示路径的方法
    ASP.NET Session详解
    关于CSS Selector的优先级
    关于汉字转拼音
    ChildActionOnly + ActionName的用法
    html中的caption是什么用
    window.location.href location.href parent.location.href
  • 原文地址:https://www.cnblogs.com/kindleheart/p/9296836.html
Copyright © 2020-2023  润新知