zoukankan      html  css  js  c++  java
  • 寻找最短路径

    #S######.#
    ......#..#
    .#.##.##.#
    .#........
    ##.##.####
    ....#....#
    .#######.#
    ....#.....
    .####.###.
    ....#...G#

    //找出最短路径是多少

     1 #include<iostream>  
     2 #include<queue>
     3 #include <utility>
     4 using namespace std;
     5 const int INF = 100000000;
     6 typedef pair<int, int> P;
     7 char maze[100][100];
     8 int N, M;
     9 int sx=0, sy=1;
    10 int gx=9, gy=8;
    11 int d[100][100];
    12 int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
    13 int bfs()
    14 {
    15     queue<P>que;
    16     for (int i = 0; i < N; i++)
    17         for (int j = 0; j < M; j++) d[i][j] = INF;
    18     que.push(P(sx, sy));
    19     d[sx][sy] = 0;
    20 
    21     while (!que.empty())
    22     {
    23         P k = que.front(); que.pop();
    24         if (k.first == gx && k.second == gy) break;
    25         
    26         for (int i = 0; i < 4; i++)
    27         {
    28             int nx = k.first + dx[i], ny = k.second + dy[i];
    29 
    30             if (0 <= nx && nx < N && 0 <= ny && ny < M&&maze[nx][ny] != '#'&&d[nx][ny] == INF)
    31             {
    32                 que.push(P(nx, ny));
    33                 d[nx][ny] = d[k.first][k.second] + 1;
    34             }
    35         }
    36     }
    37     return d[gx][gy];
    38 }
    39 int main()
    40 {
    41     N = 10, M = 10;
    42     for (int i = 0; i < N; i++)
    43         for (int j = 0; j < M; j++)
    44             cin >> maze[i][j];
    45     int res = bfs();
    46     cout << res << endl;
    47     return 0;
    48 }

    //宽度优先比深度复杂一些

  • 相关阅读:
    如何创建多线程
    Oracle导入数据表
    Oracle如何创建数据库用户
    Oracle忘记密码,如何修改密码
    Oracle如何创建表空间
    leetcode 787. K 站中转内最便宜的航班 js题解
    JS实现平衡二叉树
    typescript的安装与配置
    二分查找JS实现
    JS作用域(一):一般变量声明
  • 原文地址:https://www.cnblogs.com/kangdong/p/8728339.html
Copyright © 2011-2022 走看看