Snake in Matrix

There is a snake in an n x n matrix grid that can move in four possible directions. Each cell in the grid 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 the grid and an array of strings commands where each commands[i] is one of:

  • "UP"
  • "RIGHT"
  • "DOWN"
  • "LEFT"

It is guaranteed that the snake will remain within the grid boundaries throughout its movement.

Return the position of the final cell where the snake ends up after executing commands.

Example 1
Inputn = 2, commands = ["RIGHT","DOWN"]
Output3
Starting at cell 0 in a 2 x 2 grid, moving right reaches cell 1 and moving down reaches cell 3.
Example 2
Inputn = 3, commands = ["DOWN","RIGHT","UP"]
Output1
Starting at cell 0 in a 3 x 3 grid, moving down reaches cell 3, right reaches cell 4, and up reaches cell 1.

Constraints

  • 2 <= n <= 10
  • 1 <= commands.length <= 100
  • commands consists only of "UP", "RIGHT", "DOWN", and "LEFT".
  • The input is generated such the snake will not move outside of the boundaries.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate