GoCalf Calf 的自留地 · 昙花一现

3248. Snake in Matrix

Problem

There is a snake in an n x n matrix grid and 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 command[i] is either "UP", "RIGHT", "DOWN", and "LEFT". It’s 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.

https://leetcode.cn/problems/snake-in-matrix/

Example 1:

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

图表显示需要 JavaScript。仍可查看源码或下载文件。

Example 2:

Input: n = 3, commands = ["DOWN","RIGHT","UP"]
Output: 1
Explanation:

图表显示需要 JavaScript。仍可查看源码或下载文件。

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.

Test Cases

python
class Solution:
    def finalPositionOfSnake(self, n: int, commands: List[str]) -> int:
solution_test.py下载完整源码
py
import pytest

from solution import Solution


@pytest.mark.parametrize('n, commands, expected', [
    (2, ["RIGHT","DOWN"], 3),
    (3, ["DOWN","RIGHT","UP"], 1),
])
class Test:
    def test_solution(self, n, commands, expected):
        sol = Solution()
        assert sol.finalPositionOfSnake(n, commands) == expected

Thoughts

i = j = 0。

  • UP: i--
  • RIGHT: j++
  • DOWN: i++
  • LEFT: j--

Code

py
class Solution:
    def finalPositionOfSnake(self, n: int, commands: list[str]) -> int:
        i = j = 0
        for cmd in commands:
            if cmd == 'UP':
                i -= 1
            elif cmd == 'RIGHT':
                j += 1
            elif cmd == 'DOWN':
                i += 1
            else:
                j -= 1

        return (i * n) + j

评论需要 JavaScript。