Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Snake in Matrix

Track a snake's movement on an n×nn \times n grid from a sequence of directional commands and report its final position.

Acceptance 0%
Problem Statement

Problem

You are given an n×nn \times n matrix conceptually labeled with coordinates from top-left to bottom-right. A snake starts at the top-left cell (0,0)(0, 0).

You are also given a sequence of movement commands. Each command moves the snake by one step in one of the four cardinal directions:

  • UP
  • DOWN
  • LEFT
  • RIGHT

Apply the commands in order and determine the snake's final position.

If a move would take the snake outside the matrix, ignore that move and keep the snake in the same cell.

Return the final row and column indices after processing all commands.

Input Format

  • An integer n representing the matrix size.
  • A list of movement commands, where each command is one of UP, DOWN, LEFT, RIGHT.

Coordinates are zero-indexed with the top-left cell at (0,0)(0, 0).

Output Format

Return two integers: the final row and column index of the snake.

Constraints

  • 1n1 \le n
  • The command list may be empty.
  • Each command is one of the four directions listed above.
  • The final position must remain within the matrix bounds.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 3
commands = ["RIGHT", "RIGHT", "DOWN", "LEFT", "UP"]

Output

[0, 1]

Explanation

Start at (0, 0). After the moves, the snake ends at (0, 1).

Example 2

Input

n = 2
commands = ["LEFT", "UP", "RIGHT", "DOWN", "DOWN"]

Output

[1, 0]

Explanation

Moves that go outside the grid are ignored. The snake finishes at (1, 0).

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.