试题 基础练习 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)
欢迎交流!