Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Snake in Matrix

XPChallenge Points: 10
levelLevel: Easy

A snake moves inside an n x n matrix.
Each cell in the matrix holds a unique number based on the formula:

cellvalue= (row_index * n) + column_index

The snake always begins at position 0 (top-left corner).

You are given a list of movement commands where each command can be:

  • "UP"

  • "DOWN"

  • "LEFT"

  • "RIGHT"

The snake moves one cell in the given direction for each command.
It is guaranteed that the snake never moves outside the grid.

Return the number of the cell where the snake stops after performing all commands.

Example 1:

Input: n = 3, commands = ["RIGHT","RIGHT","DOWN"]

Output: 5

Explanation:

Grid: 0 1 2 3 4 5 6 7 8 Moves: Start at 0 RIGHT → 1 RIGHT → 2 DOWN → 5

Example 2:

Input: n = 2, commands = ["DOWN"]

Output: 2

Explanation:

Grid: 0 1 2 3 Start at 0 DOWN → 2

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result