The Eight Queens Problem

The Eight Queens Problem

Python Algortithm
The eight-queen problem is a chess-based problem: how can you place eight queens on an 8×8 chess board so that no queen can directly capture the other queens? For this purpose, no two queens can be on the same horizontal, vertical, or diagonal line. The eight-queen problem can be generalized to a more general n-queen placement problem: the size of the chessboard becomes n×n, and the number of queens becomes n.

history

The Eight Queens Problem was first proposed by chess player Max Bezzel in 1848. The first solution was given by Franz Nauck in 1850. And generalize it to the more general n-queen placement problem. Nock was also one of the first to generalize the problem to the more general n-queen placement problem.
After that, mathematicians successively studied it, including Gauss and Cantor. In 1874, S. Gundel proposed a method to solve it by determinant, which was later improved by JWL Gleisher.
In 1972, Ezge Dijkstra used this problem as an example to illustrate the power of what he called structured programming [3]. He has a very detailed description of the depth-first search backtracking algorithm.
The Eight Queens problem appeared in the famous video game The Seventh Visitor in the early 1990s and in the famous video game "Professor Layton and the Incredible Town" on the NDS platform.

code

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""


@author: gsharp
"""
#* queen problem with recurison
BOARD_SIZE = 8
 
def under_attack(col, queens):
   left = right = col
   for r, c in reversed(queens):
 #左右有冲突的位置的列号      
       left, right = left - 1, right + 1
 
       if c in (left, col, right):
           return True
   return False
 
def solve(n):
   if n == 0:
       return [[]]
 
   smaller_solutions = solve(n - 1)

   return [solution+[(n,i+1)]
       for i in xrange(BOARD_SIZE)
           for solution in smaller_solutions
               if not under_attack(i+1, solution)]
for answer in solve(BOARD_SIZE):
   print answer
       

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325305106&siteId=291194637