-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueens.py
79 lines (60 loc) · 1.5 KB
/
NQueens.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'N皇后问题求解'
__author__ = 'WH-2099'
def resultprint(result):
n=len(result)
for i in range(n):
print("-"*result[i]+"+"+"-"*(n-result[i]-1))
def posok(state,x):
"""
检测目标位置是否符合要求
"""
y=len(state)
for i in range(y):
if abs(x-state[i]) in (0,y-i):
return False
else:
return True
def findnextpos(n,state):
"""
寻找下一个符合要求的位置
"""
for x in range(n):
if posok(state,x):
if len(state)==n-1:
yield (x,)
else:
for result in findnextpos(n,state+(x,)):
yield (x,)+result
def main1():
"""
采用生成器
"""
n=int(input("How many queens?\n"))
for index,result in enumerate(findnextpos(n,())):
print(repr(index)+":")
resultprint(result)
print("\n")
def findallpos(n,state,results):
"""
采用递归方式
"""
for x in range(n):
if posok(state,x):
if len(state)==n-1:
results.append(state+(x,))
else:
findallpos(n,state+(x,),results)
def main2():
"""
递归方式
"""
n=int(input("How many queens?\n"))
results=[]
findallpos(n,(),results)
for i in range(len(results)):
print(repr(i)+":")
resultprint(results[i])
print("\n")
if __name__=="__main__":main1()