P13424 Patkice 题解
题目简述
我们模拟橡皮鸭从起点岛屿出发,沿着四个可能的方向(东、北、南、西)移动,并根据海洋洋流的方向继续移动,直到到达目标岛屿、平静海面或返回起点岛屿。
我们的目标是判断是否存在一条路径到达目标岛屿,并在存在时选择航程最短且字典序最小的方向。
方法与思路
我们模拟橡皮鸭从四个方向分别出发的路径,下面是模拟步骤:
- 第每次移动后,检查新位置是否为
x,如果是,那么此方向成功。 - 若新位置是
.或起点o,则此方向失败。 - 若新位置是洋流符号(
<、>、^、v),则根据洋流方向继续移动。
对于每个成功到达目标岛屿的方向,记录这个方向的移动步数。然后选择步数最少的方向,若步数相同则选择字典序最小的方向。
最后输出结果即可。
如果存在有效路径,输出):和最优的方向;否则,输出:(。
AC Code
#include <iostream>
#include <vector>
#include <climits>
#include <tuple>
#include <algorithm>
using namespace std;
int main() {
int r, s;
cin >> r >> s;
vector<string> grid(r);
int start_row = -1, start_col = -1;
for (int i = 0; i < r; i++) {
cin >> grid[i];
for (int j = 0; j < s; j++) {
if (grid[i][j] == 'o') {
start_row = i;
start_col = j;
}
}
}
vector<tuple<char, int, int>> dirs = {
{'E', 0, 1},
{'N', -1, 0},
{'S', 1, 0},
{'W', 0, -1}
};
bool found = false;
int min_steps = INT_MAX;
char best_dir;
for (const auto& dir : dirs) {
char d_char = get<0>(dir);
int dr = get<1>(dir);
int dc = get<2>(dir);
int nr = start_row + dr;
int nc = start_col + dc;
if (nr < 0 || nr >= r || nc < 0 || nc >= s) {
continue;
}
int steps = 1;
int cr = nr;
int cc = nc;
bool success = false;
while (true) {
if (cr < 0 || cr >= r || cc < 0 || cc >= s) {
break;
}
char cell = grid[cr][cc];
if (cell == 'x') {
success = true;
break;
}
if (cell == '.' || cell == 'o') {
break;
}
int ndr = 0, ndc = 0;
if (cell == '>') {
ndc = 1;
} else if (cell == '<') {
ndc = -1;
} else if (cell == '^') {
ndr = -1;
} else if (cell == 'v') {
ndr = 1;
}
cr += ndr;
cc += ndc;
steps++;
}
if (success) {
found = true;
if (steps < min_steps) {
min_steps = steps;
best_dir = d_char;
} else if (steps == min_steps) {
if (d_char < best_dir) {
best_dir = d_char;
}
}
}
}
if (found) {
cout << ":)" << endl;
cout << best_dir << endl;
} else {
cout << ":(" << endl;
}
return 0;
}