首页 > 代码库 > 八皇后问题

八皇后问题

语言:python

 1 # state[0] = 1 to represent a queen 2 # state = (1,3,0,2) 3 # * Q * * 4 # * * * Q  5 # Q * * * 6 # * * Q * 7 def conflict(state, nextX): 8     nextY = len(state) 9 10     for i in range(nextY):11         if abs(state[i] - nextX) in (0, nextY - i):12             return True13 14     return False

使用yield

 1 def queens(num, state): 2     if len(state) == num - 1: 3         for pos in range(num): 4             if not conflict(state, pos): 5                 yield (pos,) 6     else: 7         for pos in range(num): 8             if not conflict(state, pos): 9                 for result in queens(num, state + (pos,)):10                     yield (pos,) + result11                 #state = state + (pos,)12                 #queens(num, state)

不使用yield

 1 def queens(num, state): 2     if len(state) == num - 1: 3         tmp = [] 4         for pos in range(num): 5             if not conflict(state, pos): 6                 tmp.append((pos,)) 7         return tmp 8     else: 9         tmp = []10         for pos in range(num):11             if not conflict(state, pos):12                 for result in queens(num, state + (pos,)):13                     tmp.append((pos,) + result)14         return tmp

测试

1 print list(queens(4, ()))

 参考:

《python基础教程》 人民邮电出版社