思路一:同时放黑皇后和白皇后
思路二:放完黑皇后以后,再放白皇后
同时考虑黑皇后和白皇后
考虑index行,分三步:
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 dfs(index):
global count
if n <= 0:
return 0
if index == n:
count += 1
return
# 在第index行放置黑皇后
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"
for k in range(n):
if not col2[k] and not dia12[index + k] and not dia22[index - k] \
and board[index][k] == "1":
col2[k] = True
dia12[index + k] = True
dia22[index - k] = True
board[index][k] = "0"
dfs(index + 1)
col2[k] = False
dia12[index + k] = False
dia22[index - k] = False
board[index][k] = "1"
col1[j] = False
dia11[index + j] = False
dia21[index - j] = False
board[index][j] = "1"
return 0
dfs(0)
print(count)
第二种解法(耗时大大缩短)
思路
先在index放置黑皇后 递归,在index+1行放置黑皇后 递归到底,index == n ,这个时候说明黑皇后已经全部放置完毕(一种情况),这个时候再开始第二次dfs2(0),这个时候是放置白皇后,白皇后也放置完毕以后,一个解就找到了。代码:
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
# 在第index行放置黑皇后
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
# 在第index行放置黑皇后
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)
技术交流: