Track a snake's movement on an grid from a sequence of directional commands and report its final position.
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:
UPDOWNLEFTRIGHTApply 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.
n representing the matrix size.UP, DOWN, LEFT, RIGHT.Coordinates are zero-indexed with the top-left cell at .
Return two integers: the final row and column index of the snake.
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
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.