example05.py 1.3 KB

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