zoukankan      html  css  js  c++  java
  • POJ 3984

    POJ 3984

    BFS求最短路 + 路径输出

    路径输出的方法

    只需要用另外一个数组记录每个点的前驱是谁就行,因为BFS会产生多个后继,但最短路上的点只有唯一的前驱

    最后递归输出即可

    #include <iostream>
    #include <algorithm>
    #include <queue>
    #include <cstdio>
    using namespace std;
    const int N = 10;
    int g[N][N];
    #define endl '
    '
    struct node {
        int x,y;
    };
    int dx[4] = {0,0,1,-1};
    int dy[4] = {1,-1,0,0};
    bool vis[N][N];
    queue<node> q;
    node ans[N][N];
    void bfs() {
        q.push({0,0});
        vis[0][0] = 1;
        ans[0][0] = {-1,-1};
        while(q.size()) {
            node t = q.front();
            if(t.x == 4 && t.y == 4) return ;
            q.pop();
            for(int i = 0;i < 4; ++i) {
                int nx = dx[i] + t.x;
                int ny = dy[i] + t.y;
                if(g[nx][ny] == 0 && nx >= 0 && nx < 5 && ny >= 0 && ny < 5 && !vis[nx][ny]) {
                    q.push({nx,ny});
                    vis[nx][ny] = 1;
                    ans[nx][ny].x = t.x;
                    ans[nx][ny].y = t.y;
                }
            }
        }
    }
    void print(int x,int y) {
        if(x == 0 && y == 0) {
            printf("(%d, %d)
    ",0,0);
            return ;
        }
        print(ans[x][y].x,ans[x][y].y);
        printf("(%d, %d)
    ",x,y);
    }
    int main() {
        //ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
        for(int i = 0;i < 5; ++i)
            for(int j = 0;j < 5; ++j) 
                cin >> g[i][j];
        bfs();
        print(4,4);
        return 0;
    }
    
  • 相关阅读:
    ES6中对象新增方法
    ES6中字符串新增方法
    Laya 吐槽日志.
    汇编与反汇编工具
    Mac 软件下载地址
    红米手机 android4.4.4 root之路
    查看apk安装包信息
    文件搜索
    自动发表QQ空间说说
    批量格式化json
  • 原文地址:https://www.cnblogs.com/lukelmouse/p/12419814.html
Copyright © 2011-2022 走看看