深度优先搜索&广度优先搜索:Python实现

本文深入讲解了图搜索算法中的两种核心方法:深度优先检索(DFS)与宽度优先搜索(BFS)。通过具体实现展示了如何从起点到终点寻找路径,并详细解释了每种算法的工作原理及其应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

深度优先检索

1. definition

2. implementation

宽度优先搜索

1. definition

2. implementation


深度优先检索

1. definition

2. implementation

# Find a path from the start junction to the end junction
# Tree's structure:
# Tree = [ [],[1,2],[2,3],...,[p,q] ] where len(Tree) = n+1
# Note that there is only n junction, and Tree has a [] mean that Tree[i] represents the 
# neibouring junctions of i, i=1,2,...,n
def DFS(Tree,start,end):
    visited = set([start])
    stack = [start]
    while len(stack) > 0:
        cur = stack.pop()
        for node in Tree[cur]:
            if node not in visited:
                visited.add(node)
                stack.extend([cur,node])
                break
        if stack[-1] == end:
            return stack
        
# Note that if I want all the paths from start to end
# then 
#       if stack[-1] == end:
#           paths.append(stack)
#   return paths

宽度优先搜索

1. definition

2. implementation

# Find a path from the start junction to the end junction
# Tree's structure:
# Tree = [ [],[1,2],[2,3],...,[p,q] ] where len(Tree) = n+1
# Note that there is only n junction, and Tree has a [] mean that Tree[i] represents the 
# neibouring junctions of i, i=1,2,...,n

# Notion:This function can only find one path from a to b
def BFS(Tree,start,end):
    visited = set([start])
    queue = [start]
    parent = {start:None}
    while len(queue) > 0:
        cur = queue.pop(0)
        for node in Tree[cur]:
            if node not in visited:
                visited.add(node)
                queue.append(node)
                parent[node] = cur
    # find a path
    a = end
    path = [end]
    while a != start:
        a = parent[a]
        path.append(a)
    path.reverse()
    return path

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值