标签:http height void 迷宫 运行 mic border main 关键点
题目:求从S走到G点所需步数
#S######.# |
此代码BFS遍历顺序:
宽度优先搜索关键点:
下面贴上代码:
1 #include <iostream> 2 #include <fstream> 3 #include <queue> 4 #include <iomanip> 5 6 using namespace std; 7 typedef pair<int, int> P; 8 const int INF = 100000000; 9 int M; 10 int N; 11 int d[256][256] = { 0 }; 12 char maze[256][256] = {0}; 13 int dx[4] = { 1, 0, -1, 0 }; 14 int dy[4] = { 0, 1, 0, -1 }; 15 int sx, sy; 16 int gx, gy; 17 int BFS() 18 { 19 queue<P> que; 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)); 28 d[sx][sy] = 0; 29 while (que.size()) 30 { 31 P p = que.front(); 32 que.pop(); 33 if (p.first == gx && p.second == gy)break; 34 35 for (int i = 0; i < 4; i++) 36 { 37 int nx = p.first + dx[i], ny = p.second + dy[i]; 38 if ( maze[nx][ny] == ‘G‘ || 0 <= nx && nx < N && 0 <= ny && ny < M && maze[nx][ny] != ‘#‘ && maze[nx][ny] == ‘.‘ && d[nx][ny] == INF ) 39 { 40 que.push(P(nx, ny)); 41 d[nx][ny] = d[p.first][p.second] + 1; 42 } 43 } 44 } 45 return d[gx][gy]; 46 47 } 48 void solve( ) 49 { 50 int res = BFS(); 51 cout << endl << res << endl; 52 } 53 void solvedata() 54 { 55 ifstream filein("data1.txt"); 56 ofstream fileout("outdata.txt"); 57 58 int tmp; 59 int i = 0; 60 while (!filein.eof()) 61 { 62 filein >> tmp; 63 fileout << setw(12) << tmp; 64 cout << tmp << endl; 65 66 i++; 67 if (i == 10) 68 { 69 i = 0; 70 fileout << endl; 71 } 72 } 73 } 74 int main() 75 { 76 ifstream filein("data.txt"); 77 int i = 0; 78 while (!filein.eof()) 79 { 80 filein.getline(maze[i], 100); 81 cout << maze[i++] << endl; 82 } 83 int m = 0, n = 0; 84 while (maze[0][n])n++; 85 while (maze[m][0]) 86 { 87 for (int i = 0; i < n; i++) 88 { 89 if (maze[m][i] == ‘S‘) 90 { 91 sx = m; 92 sy = i; 93 } 94 else if (maze[m][i] == ‘G‘) 95 { 96 gx = m; 97 gy = i; 98 } 99 } 100 m++; 101 } 102 cout << "S:" << sx << " " << sy << " " << endl; 103 cout << "G:" << gx << " " << gy << " " << endl; 104 cout << "m:" << m << endl; 105 cout << "n:" << n << endl; 106 M = m; 107 N = n; 108 solve(); 109 return 0; 110 }
运行结果:
这是典型的BFS迷宫问题,也是最基本的BFS,需要熟练掌握,但并不困难。
标签:http height void 迷宫 运行 mic border main 关键点
原文地址:https://www.cnblogs.com/virgildevil/p/10358677.html