C - 矢印の道案内 / Arrow Navigation 解説 by admin
DeepSeek V3Overview
This problem asks us to determine the position where Takahashi stops after moving on a grid following the direction of arrows, halting when he either exits the grid or enters a loop.
Analysis
Takahashi moves according to the arrows on each cell, but stops in the following two cases: 1. When the destination is outside the grid 2. When the same cell is visited more than once (a loop occurs)
A straightforward approach is to simply simulate the movement by following the arrows. Since the maximum grid size is 500×500 (at most 250,000 cells), this runs sufficiently fast if implemented properly. However, recording visited cells is necessary for loop detection.
Algorithm
- Initialize the current position at (0, 0) (0-indexed)
- Prepare a set to record visited cells
- Repeat the following process:
- If the current position has already been visited, determine that a loop has occurred and stop
- Record the current position as visited
- If the arrow on the current cell is
v(south-facing):- If the cell below is within the grid, move there
- If it is outside the grid, stop
- If the arrow on the current cell is
>(east-facing):- If the cell to the right is within the grid, move there
- If it is outside the grid, stop
- Convert the position at the time of stopping to 1-indexed and output it
Complexity
- Time complexity: \(O(HW)\)
- In the worst case, every cell is visited exactly once
- Space complexity: \(O(HW)\)
- A set is needed to record visited cells
Implementation Notes
Handle grid indices as 0-indexed, and convert to 1-indexed when outputting
Use a set for loop detection to efficiently manage visited cells
Perform the out-of-grid check before moving; if the destination is outside, stop immediately
Similarly, stop immediately when a loop is detected
Source Code
def main():
import sys
data = sys.stdin.read().splitlines()
H, W = map(int, data[0].split())
grid = []
for i in range(1, H+1):
grid.append(data[i].strip())
i, j = 0, 0
visited = set()
while True:
if (i, j) in visited:
break
visited.add((i, j))
if grid[i][j] == 'v':
if i + 1 < H:
i += 1
else:
break
else: # '>'
if j + 1 < W:
j += 1
else:
break
print(i+1, j+1)
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.