python 图

简介: class Graph(object): def __init__(self,*args,**kwargs): self.node_neighbors = {} self.
class Graph(object):

    def __init__(self,*args,**kwargs):
        self.node_neighbors = {}
        self.visited = {}

    def add_nodes(self,nodelist):

        for node in nodelist:
            self.add_node(node)

    def add_node(self,node):
        if not node in self.nodes():
            self.node_neighbors[node] = []

    def add_edge(self,edge):
        u,v = edge
        if(v not in self.node_neighbors[u]) and ( u not in self.node_neighbors[v]):
            self.node_neighbors[u].append(v)

            if(u!=v):
                self.node_neighbors[v].append(u)

    def nodes(self):
        return self.node_neighbors.keys()

    # 深度优先
    def depth_first_search(self,root=None):
        order = []
        
        if root:
            self.dfs(root, order)

        for node in self.nodes():
            if not node in self.visited:
                self.dfs(node, order)

        print(order)
        return order
        
    def dfs(self, node, order):
        self.visited[node] = True
        order.append(node)
        for n in self.node_neighbors[node]:
            if not n in self.visited:
                self.dfs(n)

    # 广度优先
    def breadth_first_search(self, root=None):
        queue = []
        order = []

        if root:
            queue.append(root)
            order.append(root)
            self.bfs(queue, order)

        for node in self.nodes():
            if not node in self.visited:
                queue.append(node)
                order.append(node)
                self.bfs(queue, order)
        print(order)

        return order
        
    def bfs(self, queue, order):
        while len(queue)> 0:
            node  = queue.pop(0)
            
            self.visited[node] = True
            for n in self.node_neighbors[node]:
                if (not n in self.visited) and (not n in queue):
                    queue.append(n)
                    order.append(n)
                    
    # 找一条路径
    def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if not graph.has_key(start):
            return None
        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None
        
    # 找所有路径
    def find_all_paths(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return [path]
        if not graph.has_key(start):
            return []
        paths = []
        for node in graph[start]:
            if node not in path:
                newpaths = find_all_paths(graph, node, end, path)
                for newpath in newpaths:
                    paths.append(newpath)
        return paths
        
    # 找最短路径
    def find_shortest_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if not graph.has_key(start):
            return None
        shortest = None
        for node in graph[start]:
            if node not in path:
                newpath = find_shortest_path(graph, node, end, path)
                if newpath:
                    if not shortest or len(newpath) < len(shortest):
                        shortest = newpath
        return shortest


if __name__ == '__main__':
    g = Graph()
    g.add_nodes([i+1 for i in range(8)])
    g.add_edge((1, 2))
    g.add_edge((1, 3))
    g.add_edge((2, 4))
    g.add_edge((2, 5))
    g.add_edge((4, 8))
    g.add_edge((5, 8))
    g.add_edge((3, 6))
    g.add_edge((3, 7))
    g.add_edge((6, 7))
    print("nodes:", g.nodes())

    order = g.breadth_first_search(1)
    order = g.depth_first_search(1)
目录
相关文章
|
5月前
|
Python
针状图(python
针状图(python
47 0
|
Python
python知识点100篇系列(9)-使用python画个大风车
python知识点100篇系列(9)-使用python画个大风车
224 1
|
数据可视化 Python
25 个常用 Matplotlib 图的 Python 代码(五)
大家好,今天要分享给大家25个Matplotlib图的汇总,在数据分析和可视化中非常有用,文章较长,可以马起来慢慢练手。
25 个常用 Matplotlib 图的 Python 代码(五)
|
Python
用python画箱体图-python学习笔记21
用python画箱体图-python学习笔记21
91 0
用python画箱体图-python学习笔记21
|
Python
猪行天下之Python基础——10.1 Python常用模块(上)(一)
内容简述: 1、time和datetime模块 2、logging模块 PS:如果你想搜索安装某个模块或者发布一个自己的模块可以到移步到:pypi.org/
98 0
|
JSON 编解码 算法
猪行天下之Python基础——10.2 Python常用模块(下)(二)
内容简述: 1、json模块 2、pickle模块 3、hashlib模块 4、base64模块
151 0
|
机器学习/深度学习 存储 人工智能
图解python | 模块
在Python中,一个.py文件就称为一个模块(Module),包含很多不同功能编写成的函数。包是用来管理Python模块命名空间的形式,经常以「包.模块」的形式来导入模块。
215 0
图解python | 模块
|
数据可视化 数据挖掘 Python
Python一行代码搞定炫酷可视化,你需要了解一下Cufflinks
Python一行代码搞定炫酷可视化,你需要了解一下Cufflinks
Python一行代码搞定炫酷可视化,你需要了解一下Cufflinks
|
数据可视化 Python
25 个常用 Matplotlib 图的 Python 代码(三)
大家好,今天要分享给大家25个Matplotlib图的汇总,在数据分析和可视化中非常有用,文章较长,可以马起来慢慢练手。
25 个常用 Matplotlib 图的 Python 代码(三)
|
数据可视化 数据挖掘 Python
25 个常用 Matplotlib 图的 Python 代码(二)
大家好,今天要分享给大家25个Matplotlib图的汇总,在数据分析和可视化中非常有用,文章较长,可以马起来慢慢练手。
25 个常用 Matplotlib 图的 Python 代码(二)
下一篇
无影云桌面