标签:运行 pre abs ret 方法 time() class 问题 star
import time
"""
N 皇后问题,不同皇后不能放置在同一直线或对角线上
"""
def Nqueen(n):
# arr[i] 表示每行皇后放置的第几列
arr = [0 for i in range(n)]
cnt = 0
i = 0
resume_flag = False # 回溯标志
while i >= 0 and i <n:
if arr[i] > n-1:
i = i-1
resume_flag = True
continue
if resume_flag: # 回溯,重置未放置皇后的行的值
for k in range(i+1, n):
arr[k] = 0
resume_flag = False
arr[i] += 1
if arr[i] > n-1:
continue
attack_flag = False
for j in range(i):
if nearby([i,arr[i]], [j, arr[j]]):
attack_flag = True
break
if attack_flag:
arr[i] += 1
else:
if i == n-1:
cnt += 1
# print("arr:", arr) # 当前可能的皇后放置方法
arr[i] += 1
elif i< n-1:
i = i+1
return cnt
def nearby(a, b):
if a[0] == b[0] or a[1] == b[1]:
return True
if abs(a[0] - b[0]) == abs(a[1] - b[1]):
return True
return False
def test_nqueen():
for i in range(12):
start_time = time.time()
ret = Nqueen(i)
print("{:<4d} {:>10d} {:>10.3f}".format(i, ret, time.time()-start_time))
if __name__ == "__main__":
test_nqueen()
运行结果:
0 0 0.000
1 1 0.000
2 0 0.000
3 0 0.000
4 2 0.000
5 10 0.001
6 4 0.003
7 40 0.011
8 92 0.063
9 352 0.225
10 724 1.348
11 2680 7.262
标签:运行 pre abs ret 方法 time() class 问题 star
原文地址:https://www.cnblogs.com/rsrm/p/14141573.html