四大文化赛道完整展开
02-solution/src/cpp/main.cpp
main.cpp
站内文件视图直接读取仓库内容,Markdown 使用文档排版渲染,其余文本文件保持原始排版,方便校对训练证据链。
文件类型.cpp
10-cases/s4-jh-07-hall-navigation/02-solution/src/cpp/main.cpp
#include <algorithm>
#include <deque>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols;
if (!(cin >> rows >> cols)) {
return 0;
}
vector<string> grid(rows);
pair<int, int> start = {-1, -1};
pair<int, int> target = {-1, -1};
for (int row = 0; row < rows; ++row) {
cin >> grid[row];
for (int col = 0; col < cols; ++col) {
if (grid[row][col] == 'S') {
start = {row, col};
} else if (grid[row][col] == 'T') {
target = {row, col};
}
}
}
const int dr[4] = {1, 0, 0, -1};
const int dc[4] = {0, -1, 1, 0};
const char mark[4] = {'D', 'L', 'R', 'U'};
deque<pair<int, int>> queue;
vector<vector<int>> visited(rows, vector<int>(cols, 0));
vector<vector<tuple<int, int, char>>> parent(rows, vector<tuple<int, int, char>>(cols, {-1, -1, '?'}));
queue.push_back(start);
visited[start.first][start.second] = 1;
while (!queue.empty()) {
auto [row, col] = queue.front();
queue.pop_front();
if (make_pair(row, col) == target) {
break;
}
for (int dir = 0; dir < 4; ++dir) {
int nxt_row = row + dr[dir];
int nxt_col = col + dc[dir];
if (nxt_row < 0 || nxt_row >= rows || nxt_col < 0 || nxt_col >= cols) {
continue;
}
if (visited[nxt_row][nxt_col] || grid[nxt_row][nxt_col] == '#') {
continue;
}
visited[nxt_row][nxt_col] = 1;
parent[nxt_row][nxt_col] = {row, col, mark[dir]};
queue.push_back({nxt_row, nxt_col});
}
}
if (!visited[target.first][target.second]) {
cout << "distance=-1\n";
cout << "path=NONE\n";
return 0;
}
string path;
pair<int, int> cur = target;
while (cur != start) {
auto [prev_row, prev_col, step] = parent[cur.first][cur.second];
path.push_back(step);
cur = {prev_row, prev_col};
}
reverse(path.begin(), path.end());
cout << "distance=" << path.size() << "\n";
cout << "path=" << path << "\n";
return 0;
}