码迷,mamicode.com
首页 > 其他好文 > 详细

寻找最短路径

时间:2018-04-06 18:46:50      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:复杂   push   while   char   for   stream   inf   util   turn   

#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 }

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

寻找最短路径

标签:复杂   push   while   char   for   stream   inf   util   turn   

原文地址:https://www.cnblogs.com/kangdong/p/8728339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!