Problem Description
A snake starts at cell 0 (top-left corner) of an n x n grid and follows a sequence of commands ("UP", "RIGHT", "DOWN", "LEFT"). Each cell in the grid is numbered as grid[i][j] = (i * n) + j. The snake never leaves the grid. The task is to simulate the snake's movement and return the final cell index where it ends up.
Key Insights
- The grid is represented in a 1D manner using the index formula (row * n + col).
- The snake always starts at cell 0, which maps to position (0, 0) in row and column form.
- Each command changes the snake’s current coordinate (row, col).
- Since the snake never goes out of bounds, no boundary checks are necessary, simplifying the simulation.
- The final answer is computed by converting the final (row, col) back to a linear index.
Space and Time Complexity
Time Complexity: O(m), where m is the number of commands. Space Complexity: O(1), since only constant space is used for the row and column variables.
Solution
We approach the problem by simulating the snake's movement step by step. We start at coordinate (0, 0) corresponding to cell 0. For each command in the list, we update the row or column accordingly:
- "UP" decreases the row by 1.
- "DOWN" increases the row by 1.
- "LEFT" decreases the column by 1.
- "RIGHT" increases the column by 1. After processing all commands, we convert the final (row, col) coordinate into the required 1D cell index using the formula: index = (row * n + col).