首页 > 代码库 > 八皇后问题
八皇后问题
语言: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基础教程》 人民邮电出版社
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。