Class Solution
-
- All Implemented Interfaces:
public final class Solution3248 - Snake in Matrix.
Easy
There is a snake in an
n x nmatrixgridand can move in four possible directions. Each cell in thegridis identified by the position:grid[i][j] = (i * n) + j.The snake starts at cell 0 and follows a sequence of commands.
You are given an integer
nrepresenting the size of thegridand an array of stringscommandswhere eachcommand[i]is either"UP","RIGHT","DOWN", and"LEFT". It's guaranteed that the snake will remain within thegridboundaries throughout its movement.Return the position of the final cell where the snake ends up after executing
commands.Example 1:
Input: n = 2, commands = "RIGHT","DOWN"
Output: 3
Explanation:
Example 2:
Input: n = 3, commands = "DOWN","RIGHT","UP"
Output: 1
Explanation:
Constraints:
2 <= n <= 101 <= commands.length <= 100commandsconsists only of"UP","RIGHT","DOWN", and"LEFT".The input is generated such the snake will not move outside of the boundaries.