在 n × n 棋盘上,从左上到右每个方格上有一个棋子。我想移动一对棋子并将它们向下移动一个方格

问题描述 投票:0回答:0

(预期输出)即:将 n = 8 个棋子从对角线移动到底行一对 时间。

这里是电路板尺寸为奇数时输出的链接,即:9

import numpy as np
def move_checkers(n):

    if n < 4:
        print("Error: n should be greater than or equal to 4.")
        return
    
    #checkerboard with checkers on the main diagonal
    board = np.array([[0] * n for _ in range(n)])
    for i in range(n):
        board[i][i] = 1
        # print(board)

    print("initial = ")
    for row in board:
        print(row)
    print()
    
    # Move checkers down until they reach the bottom row
    moves = 0
    for j in range(n):
        i = 0
        while i < n-1:
            if board[i][j] == 1 and board[i+1][j] == 0:
                board[i][j], board[i+1][j] = board[i+1][j], board[i][j]
                moves += 1
                print(board[i][j], board[i+1][j] , "and", board[i+1][j], board[i+1][j])
                i = 0  # start from the top again

                print("move = ",moves)
                for row in board:
                    print(row)
                print()

            else:
                i += 1        
    
    # Check if all checkers are on the bottom row
    for j in range(n):
        if board[n-1][j] == 0:
            print("Cannot move all checkers to bottom row for n =", n)
            return
    
    print("All checkers moved to bottom row for n =", n)
    print("Total number of moves =", moves)

move_checkers(4)

我试过解决它,但我一次移动每个棋子,而我想要一对棋子在 n x n 棋盘上移动一次。

python logic puzzle
© www.soinside.com 2019 - 2024. All rights reserved.