BFS DFS Python 实现

BFS 和DFS在Python实现上一个是用Queue,pop(0)顺序打印出首结点,一个是用Stack, pop()顺序打印出尾结点。 

def BFS(start, graph):
    queue=[]
    visit=[]
    queue.append(start)
    visit.append(start)
    while queue:
        node=queue.pop(0)
        nodes=graph[node]
        for i in nodes:
            if i not in visit:
                queue.append(i)
                visit.append(i)
        print(node, end='\t')

def DFS(start, graph):
    stack=[]
    visit=[]
    stack.append(start)
    visit.append(start)
    while stack:
        node=stack.pop()
        nodes=graph[node]
        for i in nodes:
            if i not in visit:
                stack.append(i)
                visit.append(i)
        print(node, end='\t')
        
if __name__ == "__main__":
    graph = {
    'A' : ['B','C','D'],
    'B' : ['A','E','F'],
    'C' : ['A','D','F','G'],
    'D' : ['A','C','G'],
    'E' : ['B'],
    'F' : ['B','C'],
    'G' : ['C','D']
    }
    
    print("BFS search result:")
    BFS('A',graph)
    print('\n')
    print("DFS search result:")
    DFS('A',graph)

运行结果:

BFS search result:
A    B    C    D    E    F    G    

DFS search result:
A    D    G    C    F    B    E    


 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以通过使用队列来实现广度优先搜索(BFS)、深度优先搜索(DFS),以及使用优先队列来实现统一代价搜索(UCS)。 BFS(广度优先搜索): 广度优先搜索是一种层次遍历的搜索算法,通过使用队列来实现算法从根节点开始,将其加入到队列中,并将其标记为已访问。然后,从队列中取出第一个节点,并将其未访问的相邻节点加入到队列中,依此类推,直到队列为空。下面是一个Python示例代码: ```python def bfs(graph, start): visited = set() queue = [start] while queue: node = queue.pop(0) if node not in visited: print(node) visited.add(node) neighbours = graph[node] for neighbour in neighbours: queue.append(neighbour) # 调用方法 graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } bfs(graph, 'A') ``` DFS深度优先搜索): 深度优先搜索是一种通过递归实现的搜索算法算法通过深入到最底层的节点,然后回溯到上一级节点继续搜索。下面是一个Python示例代码: ```python def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) print(start) for next_node in graph[start]: if next_node not in visited: dfs(graph, next_node, visited) # 调用方法 graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } dfs(graph, 'A') ``` UCS(统一代价搜索): 统一代价搜索是一种以路径的实际代价作为搜索优先级的算法,通过使用优先队列来实现。在搜索过程中,每个节点都被赋予一个代价,并且优先队列根据这些代价来选择节点。下面是一个Python示例代码: ```python import heapq def ucs(graph, start): visited = set() queue = [(0, start)] while queue: (cost, node) = heapq.heappop(queue) if node not in visited: print(node) visited.add(node) neighbours = graph[node] for neighbour, neighbour_cost in neighbours: if neighbour not in visited: heapq.heappush(queue, (cost + neighbour_cost, neighbour)) # 调用方法 graph = { 'A': [('B', 2), ('C', 1)], 'B': [('D', 3), ('E', 2)], 'C': [('F', 4)], 'D': [], 'E': [('F', 1)], 'F': [] } ucs(graph, 'A') ``` 以上就是Python实现BFSDFS和UCS的简单示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值