There is a snake in an
n x n
matrixgrid
and can move in four possible directions. Each cell in thegrid
is 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
n
representing the size of thegrid
and an array of stringscommands
where eachcommand[i]
is either"UP"
,"RIGHT"
,"DOWN"
, and"LEFT"
. It’s guaranteed that the snake will remain within thegrid
boundaries throughout its movement.Return the position of the final cell where the snake ends up after executing
commands
.
1 | class Solution { |