zoukankan      html  css  js  c++  java
  • POJ-3984.迷宫问题(BFS + 路径输出)

    昨天中午做的这道题,结果蛙了一整天,就因为一行代码困住了,今天算是见识到自己有多菜了。流泪.jpg

      本题大意:给一个5 * 5的迷宫,1表示墙壁,0表示通路,从左上角走到右下角并输出路径。

      本题思路:主要就是BFS寻路,为了方便打印,从右下角开始进行BFS。

      注意输出时候的大坑,会有标记。

      本题代码:

     1 #include <cstdio>
     2 #include <queue>
     3 #include <map>
     4 using namespace std;
     5 
     6 typedef pair<int ,int > P;
     7 const int n = 5, INF = 1e7;
     8 int maze[n][n], d[n][n], dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
     9 P path[n][n];//用来保存每个结点的父节点,方便输出
    10 
    11 void bfs() {
    12     queue <P> s;
    13     s.push(P(4, 4));//从终点到起点方便路径打印
    14     for(int i = 0; i < n; i ++)
    15         for(int j = 0; j < n; j ++) {
    16             d[i][j] = INF;
    17             path[i][j] = P(-1, -1);
    18         }
    19     d[4][4] = 0;
    20     while(s.size()) {
    21         P p = s.front();
    22         if(p.first == 0 && p.second == 0)   break;
    23         s.pop();
    24         for(int i = 0; i < 4; i ++) {
    25             int nx = p.first + dx[i], ny = p.second + dy[i];
    26             if(nx >= 0 && nx < n && ny >= 0 && ny < n && maze[nx][ny] == 0 && d[nx][ny] == INF) {
    27                 s.push(P(nx, ny));
    28                 d[nx][ny] = d[p.first][p.second] + 1;
    29                 path[nx][ny] = P(p.first, p.second);
    30             }
    31         }
    32     }
    33 }
    34 
    35 int main () {
    36     for(int i = 0; i < n; i ++)
    37         for(int j = 0; j < n; j ++)
    38             scanf("%d", &maze[i][j]);
    39     bfs();
    40     P p = make_pair(0, 0);
    41     while(p.first != -1) {
    42         printf("(%d, %d)
    ", p.first, p.second);
    43         int tmp = p.first;//这个很坑,坑了我4个小时,修改值之前进行记录
    44         p.first = path[p.first][p.second].first;
    45         p.second = path[tmp][p.second].second;
    46     }
    47     return 0;
    48 }
    View Code
  • 相关阅读:
    hadoopfs: 未找到命令...
    WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
    centos 7 安装音乐播放器(亲测可用)(转载)
    Linux 脚本编写基础
    Zip加密
    Qt嵌入cef3关闭窗口时崩溃的问题
    C++11多线程基础
    C++11多线程(std::atomic)
    C++11多线程(thread_local)
    VS 新建RelWithDebInfo模式
  • 原文地址:https://www.cnblogs.com/bianjunting/p/10475020.html
Copyright © 2011-2022 走看看