题目大意:给你一个二维迷宫,给定入口和出口,找出最短路径。
无权图上的单源最短路,用BFS解决。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 using namespace std; 5 #define MAXN 1100 6 7 int G[MAXN][MAXN], dist[MAXN*MAXN]; 8 const int dir[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; 9 10 int main() 11 { 12 #ifdef LOCAL 13 freopen("in", "r", stdin); 14 #endif 15 int R, C; 16 while (scanf("%d%d", &R, &C) && (R || C)) 17 { 18 int k; 19 scanf("%d", &k); 20 memset(G, 0, sizeof G); 21 for (int i = 0; i < k; i++) 22 { 23 int r, n; 24 scanf("%d%d", &r, &n); 25 for (int j = 0; j < n; j++) 26 { 27 int x; 28 scanf("%d", &x); 29 G[r][x] = 1; 30 } 31 } 32 int x, y; 33 scanf("%d%d", &x, &y); 34 int src = x*C + y; 35 scanf("%d%d", &x, &y); 36 int dest = x*C + y; 37 queue<int> q; 38 memset(dist, -1, sizeof dist); 39 q.push(src); 40 dist[src] = 0; 41 while (!q.empty()) 42 { 43 int u = q.front(); 44 q.pop(); 45 if (u == dest) break; 46 int x = u / C; 47 int y = u % C; 48 for (int i = 0; i < 4; i++) 49 { 50 int dx = x + dir[i][0], dy = y + dir[i][1]; 51 int v = dx * C + dy; 52 if (dx >= 0 && dx < R && dy >= 0 && dy < C && G[dx][dy] == 0 && dist[v] == -1) 53 { 54 dist[v] = dist[u] + 1; 55 q.push(v); 56 } 57 } 58 } 59 printf("%d\n", dist[dest]); 60 } 61 return 0; 62 }