在 Python 中编写一个程序,在按给定方向滑动一次后找到下一个棋盘位置

pythonserver side programmingprogramming更新于 2026/2/15 1:48:17

假设我们有一个代表初始棋盘的 2048 游戏棋盘和一个代表滑动方向的字符串方向,我们必须找到下一个棋盘状态。正如我们在 2048 游戏中所知,我们得到了一个 4 x 4 的数字棋盘(其中一些是空的,在这里用 0 表示),我们可以向 4 个方向中的任何一个方向滑动("U"、"D"、"L"或"R")。当我们滑动时,所有数字都会尽可能地朝该方向移动,并且相同的相邻数字会相加一次。

因此,如果输入如下

direction = "L",则输出将是

为了解决这个问题,我们将遵循以下步骤:

  • 如果方向与相同"R",则

    • board := 逆时针旋转板两次

  • 否则,当方向与 "U" 相同时,则

    • board := 逆时针旋转板一次

  • 否则,当方向与 "D" 相同时,则

    • board := 逆时针旋转板三次

  • 对于 0 到 3 范围内的 i,执行

    • row := board[i] 处所有非零元素的列表

    • 对于 0 到 2 范围内的 j,执行

      • 如果 j + 1 < 行大小且 row[j] 与 row[j + 1] 相同,则

        • row[j] := row[j] * 2

        • 删除 row[j + 1]

    • 当行大小 < 4,执行

      • 在行末尾插入 0

    • board[i] := row

  • 如果方向与"R"相同,则

    • board := 逆时针旋转板两次

  • 否则,当方向与"U"相同时,则

    • board := 逆时针旋转板三次

  • 否则,当方向与"D"相同时,则

    • board := 逆时针旋转板一次

  • 返回 board

让我们看看下面的实现以便更好地理解

示例

class Solution:
   def solve(self, board, direction):
      if direction == "R":
         board = rot_anti_clock_dir(rot_anti_clock_dir(board))
      elif direction == "U":
         board = rot_anti_clock_dir(board)
      elif direction == "D":
         board = rot_anti_clock_dir(rot_anti_clock_dir(rot_anti_clock_dir(board)))

      for i in range(4):
         row = [x for x in board[i] if x]
         for j in range(3):
            if j + 1 < len(row) and row[j] == row[j + 1]:
               row[j] *= 2
               del row[j + 1]
            while len(row) < 4:
               row += [0]
            board[i] = row

      if direction == "R":
         board = rot_anti_clock_dir(rot_anti_clock_dir(board))
      elif direction == "U":
         board = rot_anti_clock_dir(rot_anti_clock_dir(rot_anti_clock_dir(board)))
      elif direction == "D":
         board = rot_anti_clock_dir(board)
      return board


def rot_anti_clock_dir(x):
   x = [[x[i][j] for i in range(4)] for j in range(4)]
   return x[::-1]

ob = Solution()
matrix = [
[2, 0, 0, 2],
[2, 2, 2, 2],
[0, 4, 2, 2],
[2, 2, 2, 0]]
print(ob.solve(matrix, "L"))

输入

matrix = [
[2, 0, 0, 2],
[2, 2, 2, 2],
[0, 4, 2, 2],
[2, 2, 2, 0]]

输出

[
[4, 0, 0, 0],
[4, 4, 0, 0],
[4, 4, 0, 0],
[4, 2, 0, 0]]

相关文章


有用资源