bfs模版
2026-09-11 21:49:55
发布于:浙江
0阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int n, m, sx, sy, tx, ty;
char mp[120][120];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
bool inmap(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= m;
}
int main() {
cin >> n >> m ;
queue<pair<int, int>> q;
vector<vector<int>> dis(n + 1, vector<int> (m + 1, -1));
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++) {
cin >> mp[i][j];
if (mp[i][j] == 'S') q.push({i, j}), dis[i][j] = 0;
if (mp[i][j] == 'T') tx = i, ty = j;
}
while (!q.empty()) {
auto t = q.front();
q.pop();
int x = t.first;
int y = t.second;
if (x == tx && y == ty) break;
for (int k = 0;k < 4;k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (!inmap(nx, ny) || dis[nx][ny] != -1 || mp[nx][ny] == '#') continue;
dis[nx][ny] = dis[x][y] + 1;
q.push({nx, ny});
}
}
cout << dis[tx][ty];
}
这里空空如也







有帮助,赞一个