C - マス目上の移動 / Movement on a Grid Editorial by admin Editorial for printing
Gemini 3.8 Flash (High)Overview
In this problem, we follow the instructions (up, down, left, right) written on the grid cells to move from cell to cell. We need to determine whether the movement terminates by stepping outside the grid, or enters an infinite loop by revisiting the same cell. If it terminates, we need to find the number of moves made.
Analysis
Takahashi moves one cell at a time according to the instruction on his current cell. The destination from each cell is always uniquely determined.
The termination condition for this movement is “the destination is outside the grid.” On the other hand, under what condition does the movement not terminate? The total number of cells is finite, at \(H \times W\). If the movement does not terminate, it will eventually revisit a cell that has already been visited in the past. Since the destination from each cell is uniquely determined, once he returns to an already visited cell, he will repeat the exact same sequence of moves forever (enter a cycle).
Therefore, we can solve the problem by performing the following simulation:
- Record that a cell has been visited each time we move.
- If the next destination is outside the grid, terminate the movement and output the current number of moves.
- If the next destination is a cell that has already been visited, determine that it has entered an infinite loop and output -1.
By keeping track of “whether each cell has been visited” in this way, since the number of visited cells is at most \(H \times W\), we can detect infinite loops and reliably terminate the program.
Algorithm
- Prepare an \(H \times W\) boolean array
visitedto track visited cells, initializing all entries tofalse. - Set the current position to \((r, c) = (0, 0)\) (0-indexed), the number of moves
steps = 0, and mark the initial position as visited (visited[0][0] = true). - Loop and compute the next cell \((nr, nc)\) according to the character \(C_{r, c}\) at the current position:
- If
U: \(nr = r - 1, nc = c\) - If
D: \(nr = r + 1, nc = c\) - If
L: \(nr = r, nc = c - 1\) - If
R: \(nr = r, nc = c + 1\)
- If
- Branch according to the next cell \((nr, nc)\):
- If it is outside the grid (\(nr < 0\) or \(nr \ge H\) or \(nc < 0\) or \(nc \ge W\)):
Movement ends. Output
stepsand terminate. - If it has already been visited (
visited[nr][nc] == true): A cycle is detected. Output-1and terminate. - Otherwise (an unvisited, valid cell):
Mark that cell as visited (
visited[nr][nc] = true), update the current position \((r, c) \leftarrow (nr, nc)\), add \(1\) tosteps, and return to Step 3.
- If it is outside the grid (\(nr < 0\) or \(nr \ge H\) or \(nc < 0\) or \(nc \ge W\)):
Movement ends. Output
Complexity
- Time Complexity: \(O(HW)\)
- Takahashi visits at most \(H \times W\) cells (the total number of cells in the grid), and determining the direction of movement and checking the visited state at each cell takes \(O(1)\) time. Since \(H \le 2000\) and \(W \le 500\), we have \(H \times W \le 10^6\), which easily runs well within the time limit.
- Space Complexity: \(O(HW)\)
- We use \(O(HW)\) memory for the array storing the grid characters and the
visitedarray managing the visited states.
- We use \(O(HW)\) memory for the array storing the grid characters and the
Implementation Notes
Preventing Out-of-Bounds Array Access: Before accessing
visited[nr][nc], always check whether \((nr, nc)\) is within the grid boundaries (\(0 \le nr < H\) and \(0 \le nc < W\)) first. If the order is reversed, it will cause an out-of-bounds access error (RE).Converting to 0-indexed: Although the problem statement uses 1-indexed coordinates (starting at \((1, 1)\)), treating it as 0-indexed (starting at \((0, 0)\)) in your program to match array indices makes the implementation simpler.
Source Code
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int h, w;
if (!(cin >> h >> w)) return 0;
vector<string> s(h);
for (int i = 0; i < h; ++i) {
cin >> s[i];
}
vector<vector<bool>> visited(h, vector<bool>(w, false));
int r = 0, c = 0;
visited[r][c] = true;
int steps = 0;
while (true) {
int nr = r, nc = c;
if (s[r][c] == 'U') nr--;
else if (s[r][c] == 'D') nr++;
else if (s[r][c] == 'L') nc--;
else if (s[r][c] == 'R') nc++;
if (nr < 0 || nr >= h || nc < 0 || nc >= w) {
cout << steps << "\n";
return 0;
}
if (visited[nr][nc]) {
cout << -1 << "\n";
return 0;
}
visited[nr][nc] = true;
r = nr;
c = nc;
steps++;
}
return 0;
}
This editorial was generated by gemini-3.8-flash-high.
posted:
last update: