C - 矢印の道案内 / Arrow Navigation Editorial by admin Editorial for printing
GPT 5.2 HighOverview
Starting from \((1,1)\), follow the arrow on each cell (south v or east >), and find the coordinates of the cell where you stop at the moment you would step outside the grid, using simulation.
Analysis
Since each move advances exactly 1 cell either south or east, the coordinates \((i,j)\) never decrease. This means you never return to the same cell, and no loops (infinite movement) can occur.
Furthermore, you can move south at most \(H-1\) times and east at most \(W-1\) times, so the total number of moves is at most \(H+W-2\). Therefore, simply simulating the movement step by step following the arrows is efficient enough.
There is no need to “compute the stopping position all at once with a formula,” nor is there any need for processing that explores all cells (e.g., computing everything with DP). The key observation is that the length of the path actually traversed is short.
Algorithm
- Start at the current position \((i,j)=(1,1)\) (use 0-indexing in implementation, so \((0,0)\)).
- Look at the character on the current cell.
- If
v, attempt to move to \((i+1,j)\)- If \(i+1>H\) (in 0-index:
i+1>=H), this is outside the grid, so stop. - Otherwise, set \(i \leftarrow i+1\).
- If \(i+1>H\) (in 0-index:
- If
>, attempt to move to \((i,j+1)\)- If \(j+1>W\) (in 0-index:
j+1>=W), stop. - Otherwise, set \(j \leftarrow j+1\).
- If \(j+1>W\) (in 0-index:
- If
- When stopped, convert the coordinates back to 1-index and output them.
For example, with \(H=2, W=3\), if the cell at \((1,3)\) is >, the next move would try to go to \((1,4)\), which is outside the grid, so you stop at \((1,3)\).
Complexity
- Time complexity: \(O(H+W)\) (at most \(H+W-2\) moves)
- Space complexity: \(O(HW)\) (storing the input grid strings)
Implementation Tips
In Python, using 0-indexing makes boundary checks cleaner as
i+1 >= H/j+1 >= W, reducing mistakes.The stopping condition is “the destination of the attempted move is outside,” so perform the range check before moving and
break.Only the final output needs to be converted to 1-index, so use
print(i+1, j+1).Source Code
import sys
def main():
input = sys.stdin.readline
H, W = map(int, input().split())
S = [input().strip() for _ in range(H)]
i = j = 0 # 0-indexed
while True:
if S[i][j] == 'v':
if i + 1 >= H:
break
i += 1
else: # '>'
if j + 1 >= W:
break
j += 1
print(i + 1, j + 1)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
posted:
last update: