zoukankan      html  css  js  c++  java
  • POJ3984 迷宫问题(最短路径存储与输出)

    迷宫问题
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 57486   Accepted: 30481

    Description

    定义一个二维数组:

    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)
     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <queue>
     5 using namespace std;
     6 #define scanf scanf_s
     7 
     8 int map[10][10];
     9 int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
    10 
    11 struct node {
    12     int x, y;
    13 };
    14 
    15 bool vis[10][10];
    16 
    17 bool check(node nxt) {
    18     if (nxt.x >= 1 && nxt.x <= 5 && nxt.y >= 1 && nxt.y <= 5 && !vis[nxt.x][nxt.y] && !map[nxt.x][nxt.y]) {
    19         return true;
    20     }
    21     else return false;
    22 }
    23 node pre[10][10];
    24 
    25 void bfs() {
    26     queue<node>Q;
    27     node st;
    28     st.x = 1; st.y = 1;
    29     Q.push(st);
    30     vis[1][1] = 1;
    31     while (!Q.empty()) {
    32         node now = Q.front();
    33         Q.pop();
    34         if (now.x == 5 && now.y == 5) {
    35             return;
    36         }
    37         for (int i = 0; i < 4; i++) {
    38             node nxt;
    39             nxt.x = now.x + dir[i][0];
    40             nxt.y = now.y + dir[i][1];
    41             if (check(nxt)) {
    42                 vis[nxt.x][nxt.y] = 1;
    43                 Q.push(nxt);
    44                 pre[nxt.x][nxt.y] = now;
    45             }
    46         }
    47 
    48     }
    49 }
    50 
    51 void print(node a) {
    52     if (a.x == 1 && a.y == 1) {
    53         printf("(0, 0)
    ");
    54         return;
    55     }
    56     print(pre[a.x][a.y]);
    57     printf("(%d, %d)
    ", a.x - 1, a.y - 1);
    58 }
    59 
    60 int main() {
    61     for (int i = 1; i <= 5; i++)
    62         for (int j = 1; j <= 5; j++)
    63             cin >> map[i][j];
    64     node ed;
    65     ed.x = 5; ed.y = 5;
    66     bfs();
    67     print(ed);
    68 
    69     return 0;
    70 }
  • 相关阅读:
    前后端交互实现(nginx,json,以及datatable的问题相关)
    前端工作笔记
    系统前端基本文件+ajax部分理解
    python(day17)二分查找
    python(day16)内置函数,匿名函数
    day15(PYTHON)推导式{生成器,字典,列表,集合}
    Javascript 模拟 new
    Javascript call和apply的模拟实现
    Javascript——bind的模拟实现
    模拟Vue 中数据双向绑定
  • 原文地址:https://www.cnblogs.com/sineagle/p/14487217.html
Copyright © 2011-2022 走看看