""" |
骑士巡逻算法 - 国际象棋中的骑士(马),按照骑士的移动规则走遍整个棋盘的每一个方格,而且每个方格只能够经过一次。 |
""" |
import sys |
SIZE = 8 |
def display(board): |
"""显示棋盘""" |
for row in board: |
for col in row: |
print (f '{col}' .rjust( 2 , '0' ), end = ' ' ) |
print () |
def patrol(board, i = 0 , j = 0 , step = 1 ): |
"""巡逻""" |
if 0 < = i < SIZE and 0 < = j < SIZE and board[i][j] = = 0 : |
board[i][j] = step |
if step = = SIZE * SIZE: |
display(board) |
sys.exit( 0 ) |
patrol(board, i + 1 , j + 2 , step + 1 ) |
patrol(board, i + 2 , j + 1 , step + 1 ) |
patrol(board, i + 2 , j - 1 , step + 1 ) |
patrol(board, i + 1 , j - 2 , step + 1 ) |
patrol(board, i - 1 , j - 2 , step + 1 ) |
patrol(board, i - 2 , j - 1 , step + 1 ) |
patrol(board, i - 2 , j + 1 , step + 1 ) |
patrol(board, i - 1 , j + 2 , step + 1 ) |
board[i][j] = 0 |
def main(): |
"""主函数""" |
board = [[ 0 ] * SIZE for _ in range (SIZE)] |
patrol(board) |
if __name__ = = '__main__' : |
main() |