Error message here!

Hide Error message here!

Error message here!

Hide Error message here!

Error message here!

Close

## n皇后问题（回溯法）——Python实现

【来源： https://www.cnblogs.com/franknihao/p/9416145.html 】具体讲解与实现

``` def check(board,row,col):
i = while i < row:
if abs(col-board[i]) in (0,abs(row-i)):
return False
i += 1
return True```
``` def EightQueen(board,row):
blen = len(board)
if row == blen:
print(board)
return True
col = while col < blen:
if check(board,row,col):
board[row] = col
if EightQueen(board,row+1):
return True
col += 1
return False```
``` def printBoard(board):
import sys
for i,col in enumerate(board):
sys.stdout.write('□ ' * col + '■ ' + '□ ' * (len(board) - 1 - col))
print( )```

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

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

此代码只能输出一种结果，实际上n皇后问题的解有多种。

https://www.cnblogs.com/aiyou-3344520/p/11696015.html