國際象棋的棋盤是8行8列共64個單元格,在棋盤上擺件八個皇后,使其不能互相攻擊,也就是說任意兩個皇后都不能處于同一行、同一列或同一斜線上。
問總共有多少種擺放方法,每一種擺放方式是怎樣的。目前,數(shù)學(xué)上可以證明八皇后問題總共有92種解。
# 遞歸版本def nQueens(n, x=0, *solution): if x == n: yield solution else: for y in range(n): if all(y != j and abs(x - i) != abs(y - j) for i, j in solution): yield from nQueens(n, x + 1, *solution, (x, y))# 迭代版本def nQueensIter(n): solution = [] j = 0 while solution or j < n: i = len(solution) while j < n and not all(y != j and abs(x - i) != abs(y - j) for x, y in enumerate(solution)): j += 1 if j < n: solution.append(j) if i == n - 1: yield tuple(enumerate(solution)) j = solution.pop() + 1 else: j = 0 else: j = solution.pop() + 1if __name__ == '__main__': def showSolution(solutions, n): for i, s in enumerate(solutions, 1): PRint("%s:/n" % i + "=" * 20) for x in range(n): for y in range(n): print('Q ' if s[x][1] == y else '_ ', end='') print() print() N = 8 showSolution(nQueens(N), N) showSolution(nQueensIter(N), N)
新聞熱點(diǎn)
疑難解答