n-queens problem (backtracking) - Python implemented

Eight queens problem
Question: chess board is 8x8 squares, each square Gerry put a piece. Queen Such pieces can attack the same row or the same column or oblique (lower left upper right lower right upper left four directions) on the pieces. On a board if you want to put eight queens so that they can not attack each other (ie not any different columns of different counterparts slash between any two), obtained one kind of (further) layout.
 
[Source: https://www.cnblogs.com/franknihao/p/9416145.html] explain in detail and implementation
 
1 def check(board,row,col):
2     i = 0
3     while i < row:
4         if abs(col-board[i]) in (0,abs(row-i)):
5             return False
6         i += 1
7     return True
 1 def EightQueen(board,row):
 2     blen = len(board)
 3     if row == blen:
 4         print(board)
 5         return True
 6     col = 0
 7     while col < blen:
 8         if check(board,row,col):
 9             board[row] = col
10             if EightQueen(board,row+1):
11                 return True
12         col += 1
13     return False
1 def printBoard(board):
2     import sys
3     for i,col in enumerate(board):
4         sys.stdout.write('' * col + '' + '' * (len(board) - 1 - col))
5         print( )

Main function call:

1 board = [ [0]*8 for row in range(8) ]  
2 EightQueen(board,0)
3 printBoard(board)

operation result:

1 [0, 4, 7, 5, 2, 6, 1, 3]
2 ■ □ □ □ □ □ □ □
3 □ □ □ □ ■ □ □ □
4 □ □ □ □ □ □ □ ■
5 □ □ □ □ □ ■ □ □
6 □ □ ■ □ □ □ □ □
7 □ □ □ □ □ □ ■ □
8 □ ■ □ □ □ □ □ □
9 □ □ □ ■ □ □ □ □

 This code can only output a consequence, there are actually more n-queens problem solution.

Guess you like

Origin www.cnblogs.com/aiyou-3344520/p/11696015.html