标签:
算法要求:
在国际象棋棋盘上(8*8)放置八个皇后,使得任意两个皇后之间不能在同一行,同一列,也不能位于同于对角线上。
国际象棋的棋盘如下图所示:
问共有多少种不同的方法,并且指出各种不同的放法。
# -*- coding:utf-8 -*- __author__ = "tyomcat" print("******八皇后问题的解决方法******") def next_col(current, n=8): length = len(current) if length == n: return dangerous = current + [item for l in [(val + length - i, val - length + i) for i, val in enumerate(current)] for item in l if item >= 0 and item <= n] for i in range(n): if i not in dangerous: yield i def queens(n=8, columns=[]): if len(columns) == n: yield columns for i in next_col(columns, n): appended = columns + [i] for c in queens(n, appended): yield c def prettyprint(solution): def line(pos,lengh=len(solution)): return ‘.‘*(pos)+‘X‘+‘.‘*(lengh-pos-1) for pos in solution: print(line(pos)) if __name__ == ‘__main__‘: i = 0 for solution in queens(8): # print(i, solution) i+=1 if i > 1: print (‘\n‘) print (‘第‘ + str(i) + ‘解‘) prettyprint(solution)
标签:
原文地址:http://www.cnblogs.com/tyomcat/p/5447752.html