Imagine a snake slithering through an n ร n grid, following your commands! ๐
The snake starts at the top-left corner (position 0) of the grid. Each cell in the grid has a unique position number calculated as: grid[i][j] = (i ร n) + j. For example, in a 3ร3 grid:
0 1 2 3 4 5 6 7 8
You'll receive a sequence of movement commands: "UP", "DOWN", "LEFT", and "RIGHT". The snake will faithfully follow each command, and it's guaranteed that the snake will never slither outside the grid boundaries.
Your task: Determine the final position number where the snake ends up after executing all commands.
Input & Output
Visualization
Time & Space Complexity
Where m is the number of commands - we process each command exactly once
Only need to store current row and column coordinates
Constraints
- 2 โค n โค 10
- 1 โค commands.length โค 100
-
commands[i] is one of
"UP","RIGHT","DOWN", and"LEFT" - The snake will remain within the grid boundaries