1. 程式人生 > >尋找最短路徑

尋找最短路徑

尋找 const 最短路徑 AI pac har spa AC utili

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

//寬度優先比深度復雜一些

尋找最短路徑