-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path013.py
More file actions
executable file
·58 lines (39 loc) · 1.1 KB
/
013.py
File metadata and controls
executable file
·58 lines (39 loc) · 1.1 KB
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
#!/usr/bin/python3
# coding:utf-8
# 回溯法-八皇后问题所有可能
def place(row, column):
"""
如果一个皇后能放在第row行和column[row]列,则返回true;否则返回false。
前row行已放置皇后
"""
i = 0
while i < row:
# 不允许同一列;不允许对角线
if column[i] == column[row] or abs(column[i]-column[row]) == abs(i-row):
return False
i += 1
return True
def n_queen(row, column, n):
"""
n皇后所有解
"""
# 初始化放置第一列
column[row] = 0
while column[row] < n:
if place(row, column):
# 最后一行放置成功
if row == n - 1:
print( column )
else:
# 下一行
n_queen( row + 1, column, n )
# 下一列
column[row] = column[row] + 1
if __name__ == '__main__':
# 棋盘的大小
n = 8
# 棋盘上的行
row = 0
# 初始化,第 row 行,第 column[row] 列放置皇后
column = [0] * n
n_queen(row, column, n)