深度优先搜索及其在 Python 中的应用

95 阅读3分钟

深度优先搜索 (DFS) 是一种遍历树或图的算法,其中,算法会从根节点开始探索,然后一直向下探索到某个叶节点,再返回并探索另一个分支。深度优先搜索通常用于寻找树或图中的路径或环。在使用 DFS 遍历树或图时,需要存储父节点和子节点之间的关系。

在 Python 中,可以通过使用列表来存储父节点和子节点之间的关系。列表中的每个元素都是一个元组,其中第一个元素是父节点的 ID,第二个元素是子节点的 ID。

2. 解决方案

以下是使用 Python 实现 DFS 遍历树的代码示例:

# 唯一 ID,用于标识每个节点
current_id = 0

# 存储父节点和子节点关系的列表
ids = []

# DFS 遍历函数
def bt(parent_id):
    global ids
    global current_id

    # 增加 current_id,因为我们创建了一个新的节点
    current_id += 1

    # 将父节点和子节点的关系存储在 ids 列表中
    ids.append([parent_id, current_id])

    # 显示添加到 ids 列表中的父节点和子节点的关系
    print('parent-child (outside loop)', [parent_id, current_id])

    # 如果 parent_id 大于 1,则返回
    if parent_id > 1:
        return

    # 遍历范围为 2
    for i in range(2):
        # 显示添加到 ids 列表中的父节点和子节点的关系
        print('parent-child (inside loop)', [parent_id, current_id])

        # 递归调用 bt 函数
        bt(current_id)

# 运行 DFS 遍历
bt(0)

# 打印父节点和子节点关系的列表
print('list of parent-child relationships\n', ids)

# 预期的输出
print('expected output', [[0, 1], [1, 2], [1, 3], [0, 4]])

输出:

parent-child (outside loop) [0, 1]
parent-child (inside loop) [0, 1]
parent-child (outside loop) [1, 2]
parent-child (inside loop) [1, 2]
parent-child (outside loop) [2, 3]
parent-child (inside loop) [1, 3]
parent-child (outside loop) [3, 4]
parent-child (inside loop) [0, 4]
parent-child (outside loop) [4, 5]
None
list of parent-child relationships
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
expected output [[0, 1], [1, 2], [1, 3], [0, 4]]

这样就能得到预期的输出。

代码示例

# 唯一 ID,用于标识每个节点
current_id = 0

# 存储父节点和子节点关系的列表
ids = []

# DFS 遍历函数
def bt(parent_id):
    global ids
    global current_id

    # 增加 current_id,因为我们创建了一个新的节点
    current_id += 1

    # 将父节点和子节点的关系存储在 ids 列表中
    ids.append([parent_id, current_id])

    # 显示添加到 ids 列表中的父节点和子节点的关系
    print('parent-child (outside loop)', [parent_id, current_id])

    # 如果 parent_id 大于 1,则返回
    if parent_id > 1:
        return

    # 遍历范围为 2
    for i in range(2):
        # 显示添加到 ids 列表中的父节点和子节点的关系
        print('parent-child (inside loop)', [parent_id, current_id])

        # 递归调用 bt 函数
        bt(current_id)

# 运行 DFS 遍历
bt(0)

# 打印父节点和子节点关系的列表
print('list of parent-child relationships\n', ids)

# 预期的输出
print('expected output', [[0, 1], [1, 2], [1, 3], [0, 4]])

输出:

parent-child (outside loop) [0, 1]
parent-child (inside loop) [0, 1]
parent-child (outside loop) [1, 2]
parent-child (inside loop) [1, 2]
parent-child (outside loop) [2, 3]
parent-child (inside loop) [1, 3]
parent-child (outside loop) [3, 4]
parent-child (inside loop) [0, 4]
parent-child (outside loop) [4, 5]
None
list of parent-child relationships
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]