zoukankan      html  css  js  c++  java
  • 图及算法----广度优先搜索

    1. 图结构的广度优先遍历的迭代算法

    # Python3 Program to print BFS traversal from a given source vertex.
    # BFS(int s) traverses vertices reachable from s. 
    from collections import defaultdict, namedtuple
    from typing import List, Dict
    
    
    class Node(object):
        def __init__(self, name=None, pi=None, dis=None, color='white'):
            self.name = name
            self.pi = pi
            self.dis = dis
            self.color = color
    
    
    class Graph: 
        def __init__(self): 
            # This class represents a directed graph using adjacency list representation
            self.graph: Dict[str, List[str]] = defaultdict(list)
            self.nodes: Dict[str, Node] = dict()
        
        def addEdge(self, u, v): 
            self.graph[str(u)].append(str(v))
            self.nodes.update({str(it): Node(name=str(it)) for it in [u, v] if str(it) not in self.nodes})
            
        def BFS(self, u): 
            queue = []  
            # 维护前驱节点队列, 节点第一次被访问是作为后继节点访问的,第二次是作为加入队列的目的是为了作为前驱节点再次访问
            # Mark the source node as visited and enqueue it 
            queue.append(str(u)) 
            self.nodes[str(u)].color = 'gray'
            while queue: 
                u = queue.pop(0)  # 弹出前驱节点
                print(u, end=">>>>
     ") 
                # 获取弹出节点u的邻居节点. 若其未被访问, 标记为访问并将其入队列,都是相邻节点入列,正好满足层层迭代
                for v in self.graph[u]: 
                    if self.nodes[v].color == 'white': 
                        print(v, self.nodes[v].color)
                        self.nodes[v].color = 'gray'
                        queue.append(v) 
                self.nodes[str(u)].color = 'black'
                
                     
    # Create a graph given in the above diagram 
    g = Graph() 
    g.addEdge(0, 1) 
    g.addEdge(0, 2) 
    g.addEdge(1, 2) 
    g.addEdge(2, 0) 
    g.addEdge(2, 3) 
    g.addEdge(3, 3) 
    
    print("Following is Breadth First Traversal (starting from vertex 2)") 
    g.BFS(2) 

  • 相关阅读:
    VBS修改本机的账号密码
    验证是否为全局编录服务器
    通过CMD命令设置网络参数
    VBS映射网络驱动器 映射网络驱动器
    命令提示符映射网络驱动器
    获得域内包括工作组内的所有计算机及其信息
    VirtualBox安装Redhat9.0
    启动和停止Oracle服务bat脚本
    Vim常用命令
    使用为知笔记客户端发布博客到【博客园】
  • 原文地址:https://www.cnblogs.com/wdmx/p/10073846.html
Copyright © 2011-2022 走看看