Python程式:查詢滑動給定方向一次後的下一個棋盤位置


假設我們有一個表示初始棋盤的 2048 遊戲棋盤和一個表示滑動方向的字串,我們需要找到下一個棋盤狀態。眾所周知,在 2048 遊戲中,我們得到一個 4 x 4 的數字棋盤(其中一些是空的,這裡用 0 表示),我們可以向四個方向中的任意一個滑動(“U”、“D”、“L”或“R”)。當我們滑動時,所有數字都儘可能地向該方向移動,並且相同的相鄰數字恰好加起來一次。

因此,如果輸入類似於

direction = "L",則輸出將為

為了解決這個問題,我們將遵循以下步驟

  • 如果 direction 等於 "R",則

    • board := 將棋盤逆時針旋轉兩次

  • 否則,當 direction 等於 "U" 時,則

    • board := 將棋盤逆時針旋轉一次

  • 否則,當 direction 等於 "D" 時,則

    • board := 將棋盤逆時針旋轉三次

  • 對於 i 從 0 到 3,執行

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

    • 對於 j 從 0 到 2,執行

      • 如果 j + 1 小於 row 的大小且 row[j] 等於 row[j + 1],則

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

        • 移除 row[j + 1]

    • 當 row 的大小小於 4 時,執行

      • 在 row 的末尾插入 0

    • board[i] := row

  • 如果 direction 等於 "R",則

    • board := 將棋盤逆時針旋轉兩次

  • 否則,當 direction 等於 "U" 時,則

    • board := 將棋盤逆時針旋轉三次

  • 否則,當 direction 等於 "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]]

更新於: 2020年11月9日

133 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告