CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example05.py
Views: 729
1
"""
2
递归回溯法:叫称为试探法,按选优条件向前搜索,当搜索到某一步,
3
发现原先选择并不优或达不到目标时,就退回一步重新选择。
4
经典问题:骑士巡逻
5
"""
6
import os
7
import sys
8
import time
9
10
SIZE = 5
11
total = 0
12
13
14
def print_board(board):
15
# os.system('clear')
16
for row in board:
17
for col in row:
18
print(str(col).center(4), end='')
19
print()
20
21
22
def patrol(board, row, col, step=1):
23
if row >= 0 and row < SIZE and \
24
col >= 0 and col < SIZE and \
25
board[row][col] == 0:
26
board[row][col] = step
27
if step == SIZE * SIZE:
28
global total
29
total += 1
30
print(f'第{total}种走法: ')
31
print_board(board)
32
patrol(board, row - 2, col - 1, step + 1)
33
patrol(board, row - 1, col - 2, step + 1)
34
patrol(board, row + 1, col - 2, step + 1)
35
patrol(board, row + 2, col - 1, step + 1)
36
patrol(board, row + 2, col + 1, step + 1)
37
patrol(board, row + 1, col + 2, step + 1)
38
patrol(board, row - 1, col + 2, step + 1)
39
patrol(board, row - 2, col + 1, step + 1)
40
board[row][col] = 0
41
42
43
def main():
44
board = [[0] * SIZE for _ in range(SIZE)]
45
patrol(board, SIZE - 1, SIZE - 1)
46
47
48
if __name__ == '__main__':
49
main()
50
51