*/-->
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
pre.src {background-color: Black; color: White;}
bfs:求最短路径的长度
题目:迷宫的最短路径
给定一个大小为N x M的迷宫。迷宫由通道和墙壁组成。每一步可以向邻接的上下左右四格的通道
移动。请求出从起点到终点所需的最小步数
#S######.# ......#..# .#.##.##.# .#........ ##.##.#### ....#....# .#######.# .#######.# ....#..... .####.###. ....#...G#
输出 22
#include <cstdio> #include <queue> using namespace std; const int inf = 0x3fffffff; const int maxn = 105; char g[maxn][maxn]; int sx, sy; int gx, gy; int n; int m; int d[maxn][maxn]; int bfs() { queue<pair<int, int> > que; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { d[i][j] = inf; } } que.push(make_pair(sx, sy)); d[sx][sy] = 0; while (que.size()) { pair<int, int> p = que.front(); que.pop(); if (p.first == gx && p.second == gy) { break; } int dx[4] = { 1, 0, -1, 0 }; int dy[4] = { 0, 1, 0, -1 }; for (int i = 0; i < 4; i++) { int nx = p.first + dx[i]; int ny = p.second + dy[i]; if (0 <= nx && nx < n && 0 <= ny && ny < m && g[nx][ny] != ‘#‘ && d[nx][ny] == inf) { que.push(make_pair(nx, ny)); d[nx][ny] = d[p.first][p.second] + 1; } } } return d[gx][gy]; } void solve() { int res = bfs(); printf("%d\n", res); } int main(void) { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%c", &g[i][j]); // 如果超时可以考虑用 scanf("%s", g[i]); if (g[i][j] == ‘S‘) { sx = i; sy = j; } else if (g[i][j] == ‘G‘) { gx = i; gy = j; } } getchar(); } solve(); return 0; }
时间: 2024-10-13 11:57:12