【蓝桥杯Python】基础练习27:2n皇后问题

试题 基础练习 2n皇后问题




题目


资源限制

时间限制: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


样例输出

0



解答

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)



欢迎交流!
WeChat QRcode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CharlesWYQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值