Track a snake's movement on an grid from a sequence of directional commands and report its final position.
Problem
You are given an matrix conceptually labeled with coordinates from top-left to bottom-right. A snake starts at the top-left cell .
You are also given a sequence of movement commands. Each command moves the snake by one step in one of the four cardinal directions:
UPDOWNLEFTRIGHT
Apply the commands in order and determine the snake's final position.
If a move would take the snake outside the matrix, ignore that move and keep the snake in the same cell.
Return the final row and column indices after processing all commands.
Input Format
- An integer
nrepresenting the matrix size. - A list of movement commands, where each command is one of
UP,DOWN,LEFT,RIGHT.
Coordinates are zero-indexed with the top-left cell at .
Output Format
Return two integers: the final row and column index of the snake.
Constraints
- The command list may be empty.
- Each command is one of the four directions listed above.
- The final position must remain within the matrix bounds.
Example 1
Input
n = 3 commands = ["RIGHT", "RIGHT", "DOWN", "LEFT", "UP"]
Output
[0, 1]
Explanation
Start at (0, 0). After the moves, the snake ends at (0, 1).
Example 2
Input
n = 2 commands = ["LEFT", "UP", "RIGHT", "DOWN", "DOWN"]
Output
[1, 0]
Explanation
Moves that go outside the grid are ignored. The snake finishes at (1, 0).
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.