码迷,mamicode.com
首页 > 其他好文 > 详细

八皇后问题

时间:2014-08-05 18:21:09      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   os   for   问题   div   

语言: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 True
13 
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,) + result
11                 #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基础教程》 人民邮电出版社

八皇后问题,布布扣,bubuko.com

八皇后问题

标签:style   blog   color   使用   os   for   问题   div   

原文地址:http://www.cnblogs.com/mess4u/p/3892416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!