第一个题解(包AC)
2026-05-29 19:21:17
发布于:广东
7阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int n, m;
char mp[105][105];
bool vis[105][105];
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
vector<pair<int, int>> path; // 存当前路径
bool found = false; // 是否已找到终点
void dfs(int x, int y) {
if (found) return; // 已找到,停止
if (x < 0 || x >= n || y < 0 || y >= m) return;
if (mp[x][y] == 'X') return;
if (vis[x][y]) return;
vis[x][y] = true;
path.push_back({x, y}); // 记录当前坐标
if (mp[x][y] == 'T') {
// 输出整条路径
for (auto p : path) {
cout << p.first << " " << p.second << endl;
}
cout << "YES" << endl;
found = true;
return;
}
for (int i = 0; i < 4; i++) {
dfs(x + dx[i], y + dy[i]);
}
path.pop_back(); // 回溯,移除当前坐标
}
int main() {
cin >> n >> m;
int sx, sy;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> mp[i][j];
if (mp[i][j] == 'S') {
sx = i;
sy = j;
}
}
}
dfs(sx, sy);
if (!found) cout << "NO" << endl;
return 0;
}
这里空空如也







有帮助,赞一个