• 迷宫问题


    迷宫的最短路径

      给定一个大小为N×M的迷宫。迷宫由通道和墙壁组成,每一步可以向邻接的上下左右四个的通道移动。请求出从起点到终点所需的最小步数。请注意,本题假定从起点一定可以移动到终点。(N,M≤100)('#', '.' , 'S', 'G'分别表示墙壁、通道、起点和终点)

    输入:

    10 10

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

    输出:

    22

    思路:

    在这个题目中运用bfs的想法,对它进行解析。当你找到一个点时就将这个点保存到队列中。

    代码:

     1 #include<iostream>
     2 #include<queue>
     3 #define MAX_N 10050
     4 using namespace std;
     5 const int INF = 100000000;
     6 typedef pair<int, int>P;
     7 
     8 char maze[MAX_N][MAX_N+1];
     9 int N,M;
    10 int sx,sy;  //起点
    11 int gx,gy;  //终点
    12 int d[MAX_N][MAX_N];  //到各个位置的最短距离的数组
    13 
    14 int dx[4]= {1,0,-1,0}, dy[4]= {0,1,0,-1};
    15 
    16 int bfs()
    17 {
    18     queue<P> que;
    19     //把所有的位置初始化为INF
    20     for(int i=0; i<N; i++)
    21     {
    22         for(int j=0; j<M; j++)
    23         {
    24             d[i][j]=INF;
    25         }
    26     }
    27     que.push(P(sx,sy));   //push压入队列
    28     d[sx][sy]=0;
    29     //直到队列为空
    30     while(que.size())
    31     {
    32         P p=que.front();
    33         que.pop();
    34         if(p.first == gx && p.second == gy) break;
    35 
    36         for(int i=0; i<4; i++)
    37         {
    38             int nx=p.first+dx[i],ny=p.second+dy[i];
    39 
    40             if(nx>=0&&nx<N&&ny>=0&&ny<M&&maze[nx][ny] != '#'&&
    41                     d[nx][ny]==INF)
    42             {
    43                 que.push(P(nx,ny));
    44                 d[nx][ny] = d[p.first][p.second] + 1;
    45             }
    46         }
    47     }
    48     return d[gx][gy];
    49 }
    50 int main()
    51 {
    52     cin>>N>>M;
    53     for(int i=0; i<N; i++)
    54     {
    55         for(int j=0; j<M; j++)
    56         {
    57             cin>>maze[i][j];
    58             if (maze[i][j] == 'S')
    59             {
    60                 sx=i;
    61                 sy=j;
    62             }
    63             if(maze[i][j]=='G')
    64             {
    65                 gx=i;
    66                 gy=j;
    67             }
    68         }
    69     }
    70     int res=bfs();
    71     cout<<res<<endl;
    72 }
  • 相关阅读:
    选择排序
    散列冲突解决方案
    string stringbuffer StringBuilder
    java关键字
    Vector
    What is the difference between book depreciation and tax depreciation?
    Type of Asset Books in Oracle Fixed Assets
    questions
    Oracle Express 11g
    iot
  • 原文地址:https://www.cnblogs.com/Yinchen-One/p/8697946.html
Copyright © 2020-2023  润新知