AcWing 844 走迷宫
题目链接:https://www.acwing.com/problem/content/846/
给定一个n*m的二维整数数组,用来表示一个迷宫,数组中只包含0或1,其中0表示可以走的路,1表示不可通过的墙壁。
最初,有一个人位于左上角(1, 1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角(n, m)处,至少需要移动多少次。
数据保证(1, 1)处和(n, m)处的数字为0,且一定至少存在一条通路。
输入格式
第一行包含两个整数n和m。
接下来n行,每行包含m个整数(0或1),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
1≤n,m≤1001≤n,m≤100
输入样例:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出样例:8
代码一(STL queue)
1 #include <iostream> 2 #include <algorithm> 3 #include <queue> 4 5 6 using namespace std; 7 8 const int maxn = 1e2 + 10; 9 int G[maxn][maxn]; 10 int dx[4] = { 0, 0, 1, -1 }; 11 int dy[4] = { 1, -1, 0, 0 }; 12 bool inq[maxn][maxn]; 13 int m, n; 14 15 struct node { 16 int x; 17 int y; 18 int step; 19 }; 20 21 queue<node>q; 22 node S; 23 24 bool judge(int x, int y) { 25 if (x < 0 || y < 0 || x >= m || y >= n || inq[x][y] || G[x][y] != 0) 26 return false; 27 return true; 28 } 29 30 void BFS() { 31 q.push(S); 32 while (!q.empty()) { 33 node t = q.front(); 34 q.pop(); 35 if (t.x == m - 1 && t.y == n - 1) { 36 cout << t.step << endl; 37 return; 38 } 39 for (int i = 0; i < 4; i++) { 40 int newX = t.x + dx[i]; 41 int newY = t.y + dy[i]; 42 if (judge(newX, newY)) { 43 node Node; 44 Node.x = newX; 45 Node.y = newY; 46 Node.step = t.step + 1; 47 q.push(Node); 48 inq[newX][newY] = true; 49 } 50 } 51 } 52 } 53 54 int main() { 55 cin >> m >> n; 56 for (int i = 0; i < m; i++) 57 for (int j = 0; j < n; j++) 58 cin >> G[i][j]; 59 S.x = 0; 60 S.y = 0; 61 S.step = 0; 62 BFS(); 63 return 0; 64 }
代码二 (数组模拟队列)
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 5 6 using namespace std; 7 8 typedef pair<int, int>PII; 9 const int N = 105; 10 int m, n; 11 int g[N][N]; 12 int d[N][N]; 13 PII q[N * N]; 14 15 bool judge(int x, int y) { 16 if (x < 0 || x >= n || y < 0 || y >= m || g[x][y] != 0 || d[x][y] != -1) 17 return false; 18 return true; 19 } 20 21 int BFS() { 22 int hh = 0, tt = 0; 23 q[0] = {0, 0}; 24 memset(d, -1, sizeof d); 25 d[0][0] = 0; 26 int dx[] = {-1, 0, 1, 0}; 27 int dy[] = {0, -1, 0, 1}; 28 while (hh <= tt) { 29 auto t = q[hh++]; 30 for (int i = 0; i < 4; i++) { 31 int x = t.first + dx[i]; 32 int y = t.second + dy[i]; 33 if (judge(x, y)) { 34 d[x][y] = d[t.first][t.second] + 1; 35 q[++tt] = {x, y}; 36 } 37 } 38 } 39 return d[n - 1][m - 1]; 40 } 41 42 int main() { 43 cin >> n >> m; 44 for (int i = 0; i < n; i++) 45 for(int j = 0; j < m; j++) 46 cin >> g[i][j]; 47 cout << BFS() << endl; 48 return 0; 49 }