Tap here to switch tabs
Problem
Submissions

Problem: Snake in Matrix

med
30 min
Try to solve the Snake in Matrix problem.

Statement

There is an n×nn \times n grid numbered from 00 to n2−1n^2 - 1, where each cell at row rr and column cc holds the value (r×n)+c(r \times n) + c.

A snake starts at cell (0,0)(0, 0) with a value of 00. You are given an array of strings commands that describes the movement of the snake at each step:

  • "UP": moves one cell up to (r−1,c)(r - 1, c)

  • "DOWN": moves one cell down to (r+1,c)(r + 1, c)

  • "LEFT": moves one cell left to (r,c−1)(r, c - 1)

  • "RIGHT": moves one cell right to (r,c+1)(r, c + 1)

Return the value of the cell where the snake ends up after executing all the given commands.

Constraints:

  • 2≤2 \leq n ≤10\leq 10

  • 1≤1 \leq commands.length ≤100\leq 100

  • commands consists only of "UP", "RIGHT", "DOWN", and "LEFT".

  • The input is generated such that the snake will not move outside of the boundaries.

⋮
Tap here to switch tabs
Problem
Submissions

Problem: Snake in Matrix

med
30 min
Try to solve the Snake in Matrix problem.

Statement

There is an n×nn \times n grid numbered from 00 to n2−1n^2 - 1, where each cell at row rr and column cc holds the value (r×n)+c(r \times n) + c.

A snake starts at cell (0,0)(0, 0) with a value of 00. You are given an array of strings commands that describes the movement of the snake at each step:

  • "UP": moves one cell up to (r−1,c)(r - 1, c)

  • "DOWN": moves one cell down to (r+1,c)(r + 1, c)

  • "LEFT": moves one cell left to (r,c−1)(r, c - 1)

  • "RIGHT": moves one cell right to (r,c+1)(r, c + 1)

Return the value of the cell where the snake ends up after executing all the given commands.

Constraints:

  • 2≤2 \leq n ≤10\leq 10

  • 1≤1 \leq commands.length ≤100\leq 100

  • commands consists only of "UP", "RIGHT", "DOWN", and "LEFT".

  • The input is generated such that the snake will not move outside of the boundaries.