8皇后之谜-使用python的递归
我正试图解决这个问题,也被称为n皇后算法 我的函数应该计算在NxN板上放置N个皇后的合法方式有多少 我差一点就搞定了,但我不得不做一些难看的补丁来让它正常工作。 你能帮我修一下吗 简要介绍我所做的工作: 试图找出在NxN表中设置N个皇后的合法方法有多少, 我试图在(N-1)xN情况下使用递归解决问题(删除第一列) 至于同一列上不允许有两个皇后,我使用的列表长度是N。 每个单元格代表一列,我在每列中设置设置皇后所在位置的行号 比如说,8皇后之谜-使用python的递归,python,n-queens,Python,N Queens,我正试图解决这个问题,也被称为n皇后算法 我的函数应该计算在NxN板上放置N个皇后的合法方式有多少 我差一点就搞定了,但我不得不做一些难看的补丁来让它正常工作。 你能帮我修一下吗 简要介绍我所做的工作: 试图找出在NxN表中设置N个皇后的合法方法有多少, 我试图在(N-1)xN情况下使用递归解决问题(删除第一列) 至于同一列上不允许有两个皇后,我使用的列表长度是N。 每个单元格代表一列,我在每列中设置设置皇后所在位置的行号 比如说, [0, 4, 7, 5, 2, 6, 1, 3] 意味着:
[0, 4, 7, 5, 2, 6, 1, 3]
意味着:
- 第0列–皇后放置在第0行
- 第1列–皇后放置在第4行
- 第2列–皇后放置在第7行
- 第3列–皇后放置在第5行
- 第4列–皇后放置在第2行
- 第5列–皇后放置在第6行
- 第6列–皇后放置在第1行
- 第7列–皇后放置在第3行
sum
的全局变量,仅当递归达到完全放置的皇后排列(这是合法的)时才增加它
def is_available(n, table, column, N):
return not any(t in (n, n - i, n + i)
for t, i in zip(table, range(column, 0, -1)))
def queens_sum(N):
table = [0]*N
global sum
sum = 0
solve(N, table, 0, len(table))
return sum
def solve(N, table, column, end):
global sum
if column == end:
sum += 1
return None
for n in range(N):
# if no other queen can attack here, place a queen in this row
if is_available(n, table, column, N):
table[column] = n
# Omit the current column at the start
solve(N, table, column+1, end)
#else: we can't place queen here, we should abort this direction
# do nothing
对于N=8
我得到sum=92
。。因此,我知道它是有效的,但我想避免使用这个全局计数器
您能帮忙吗?您可以使用solve的返回值来跟踪总和:
def queens_sum(N):
return solve(N, [0]*N, 0, N)
def solve(N, table, column, end):
if column == end:
return 1
sum = 0
for n in range(N):
# if no other queen can attack here, place a queen in this row
if is_available(n, table, column, N):
table[column] = n
# Omit the current column at the start
sum += solve(N, table, column+1, end)
#else: we can't place queen here, we should abort this direction
# do nothing
return sum
谢谢你,加雷斯!修正了。小调:
sum
是一个非常有用的内置函数的名称,因此对于您自己的变量来说是个坏名字。哦,当然。谢谢