天天看點

【藍橋杯Python】基礎練習27:2n皇後問題題目解答

試題 基礎練習 2n皇後問題

目錄

  • 題目
    • 資源限制
    • 問題描述
    • 輸入格式
    • 輸出格式
    • 樣例輸入
    • 樣例輸出
    • 樣例輸入
    • 樣例輸出
  • 解答
    • Python源代碼:

題目

資源限制

時間限制:1.0s 記憶體限制:512.0MB

問題描述

給定一個n*n的棋盤,棋盤中有一些位置不能放皇後。現在要向棋盤中放入n個黑皇後和n個白皇後,使任意的兩個黑皇後都不在同一行、同一列或同一條對角線上,任意的兩個白皇後都不在同一行、同一列或同一條對角線上。問總共有多少種放法?n小于等于8。

輸入格式

輸入的第一行為一個整數n,表示棋盤的大小。

接下來n行,每行n個0或1的整數,如果一個整數為1,表示對應的位置可以放皇後,如果一個整數為0,表示對應的位置不可以放皇後。

輸出格式

輸出一個整數,表示總共有多少種放法。

樣例輸入

4

1 1 1 1

1 1 1 1

1 1 1 1

1 1 1 1

樣例輸出

2

樣例輸入

4

1 0 1 1

1 1 1 1

1 1 1 1

1 1 1 1

樣例輸出

解答

Python源代碼:

"""
Author: CharlesWYQ Time: 2021/3/5 17:05
Name: BASIC-27 VIP試題 2n皇後問題(*)
"""
from collections import defaultdict

n = int(input())
board = []
for i in range(n):
    board.append(input().split())
col1 = defaultdict(bool)
dia11 = defaultdict(bool)
dia21 = defaultdict(bool)
col2 = defaultdict(bool)
dia12 = defaultdict(bool)
dia22 = defaultdict(bool)
count = 0


def dfs2(index):
    global count
    if index == n:
        count += 1
        return

    for j in range(n):
        if not col2[j] and not dia12[index + j] and not dia22[index - j] \
                and board[index][j] == "1":
            col2[j] = True
            dia12[index + j] = True
            dia22[index - j] = True
            board[index][j] = "0"
            dfs2(index + 1)
            col2[j] = False
            dia12[index + j] = False
            dia22[index - j] = False
            board[index][j] = "1"

    return 0


def dfs1(index):
    if n <= 0:
        return 0
    if index == n:
        dfs2(0)
        return

    for j in range(n):
        if not col1[j] and not dia11[index + j] and not dia21[index - j] \
                and board[index][j] == "1":
            col1[j] = True
            dia11[index + j] = True
            dia21[index - j] = True
            board[index][j] = "0"
            dfs1(index + 1)
            col1[j] = False
            dia11[index + j] = False
            dia21[index - j] = False
            board[index][j] = "1"

    return 0


dfs1(0)
print(count)

           

歡迎交流!

【藍橋杯Python】基礎練習27:2n皇後問題題目解答