Python回溯算法--笔记

#被记住的永远是疯子!

回溯算法

    • 基本思想
    • 骑士巡逻案例
一道笔试题,题目的具体内容记不清楚了,但出现在笔试题中的算法的重要性不言而喻,记此笔记方便日后查阅。文章内容来源于github中jackfrued分享的课程内容。

基本思想

称为试探法,按选优条件向前搜索,当搜索到某一步,发现原先选择并不优或达不到目标时,就退回一步重新选择,比较经典的问题包括骑士巡逻、八皇后和迷宫寻路等。

骑士巡逻案例

简单的描述一下骑士巡逻,在一个棋盘中,有一个骑士,他是个骑士就会骑着马,众所周知,马走日,因此骑士巡逻的步骤就是:骑士从棋盘中的某一点出发,按日字型的步伐遍历棋盘的每一个点而不重复。
下面的案例代码指定棋盘右下角为骑士的出发点,并未随机。

import sys
import time

# 定义棋盘大小
SIZE = 5
# 定义一个全局变量,用于记录第total种巡游方式。
total = 0

def print_board(board):
    for row in board:
        for col in row:
            print(str(col).center(4), end='')
        print()

def patrol(board, row, col, step=1):
    if row >= 0 and row < SIZE and \
        col >= 0 and col < SIZE and \
        board[row][col] == 0:
        board[row][col] = step
        # 当最后一步恰好等于 25(本案例5*5)时,打印输出巡游路线
        if step == SIZE * SIZE:
            global total
            total += 1
            print(f'第{total}种走法: ')
            print_board(board)
        # 下一步可能会走的位置
        patrol(board, row - 2, col - 1, step + 1)
        patrol(board, row - 1, col - 2, step + 1)
        patrol(board, row + 1, col - 2, step + 1)
        patrol(board, row + 2, col - 1, step + 1)
        patrol(board, row + 2, col + 1, step + 1)
        patrol(board, row + 1, col + 2, step + 1)
        patrol(board, row - 1, col + 2, step + 1)
        patrol(board, row - 2, col + 1, step + 1)
        board[row][col] = 0

def main():
	# 生成5*5的棋盘
    board = [[0] * SIZE for _ in range(SIZE)]
    #设定巡游起点为索引(4,4)
    patrol(board, SIZE - 1, SIZE - 1)

if __name__ == '__main__':
    main()

参考资料:
https://github.com/jackfrued/Python-100-Days/blob/master/Day16-20/16-20.Python语言进阶.md

你可能感兴趣的:(Python回溯算法--笔记)