2n皇后的两种解法 python(全面解析),第二种耗时大大缩短

Manda ·
更新时间:2024-09-21
· 519 次阅读

题目

在这里插入图片描述

两种思路

思路一:同时放黑皇后和白皇后
思路二:放完黑皇后以后,再放白皇后

第一种解法(耗时较长)

同时考虑黑皇后和白皇后
考虑index行,分三步:

在index行放置黑皇后 在index行放置白皇后 递归,在index+1重复上述操作 递归结束条件 index == n
代码 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)

技术交流:
mark


作者:CodingFishzhi



n皇后 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号