利用回溯法求解八皇后(N皇后)问题也是非常经典的运用。
八皇后问题,是一个古老而著名的问题,是回溯算法的典型案例。
该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:
在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。
高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。
- #coding:utf-8
- #Define 'N' queens problem:
- n = 8
- #initiate:
- chest = [[0] * n for i in range(n)] #define the matrix
- result = [] #put all the results in the list.
- tmp = [] #put the queens' position in tmp as "1-D" list.
- queen = 0 #check the queens has been put.
- c = 0 #calculate the solutions.
- #define reset function:
- def reset():
- global chest, tmp, queen
- chest = [[0] * n for i in range(n)]
- tmp = []
- queen = 0
- #define the position (x,y) can put the queen or not:
- def check(x,y):
- if max(chest[x]) == 1:
- return False
- if max([chest[i][y] for i in range(n)]) == 1:
- return False
- for i in range(n):
- for j in range(n):
- if i+j == x+y or i-j == x-y:
- if chest[i][j] == 1:
- return False
- return True
- #define the main loop to put the queens:
- def main():
- global c
- if len(tmp) == n:
- result.append(tmp)
- c += 1
- print ('Solution %d:' % c)
- show = [[0] * n for i in range(n)]
- for i in range(n):
- show[i][tmp[i]] = 1
- print (show[i])
- print ()
- reset()
- for i in range(n):
- y = i
- x = len(tmp)
- if check(x,y) and tmp+[y] not in result:
- tmp.append(y)
- chest[x][y] = 1
- main()
- try:
- chest[x][y] = 0
- tmp.remove(y)
- except:
- print ('Total Solution %d, done!' % len(result))
- exit()
- if __name__ == "__main__":
- main()
复制代码
当n=8时(八皇后),输出:
Solution 1:
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
Solution 2:
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
中间省略N个解
Solution 91:
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 1, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
Solution 92:
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 1, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
Total Solution 92, done! |