zoukankan      html  css  js  c++  java
  • 八皇后问题

    语言: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基础教程》 人民邮电出版社

  • 相关阅读:
    纸牌排序
    将年份转换成天干地支
    猜算式
    字符串的简单处理
    九宫格填数字
    扫雷
    嗨喽
    Input.GetAxis与Input.GetAxisRaw区别
    C#中(int)、int.Parse()、int.TryParse()和Convert.ToInt32()的区别
    开发游戏所需知识(知乎转载)
  • 原文地址:https://www.cnblogs.com/mess4u/p/3892416.html
Copyright © 2011-2022 走看看