数据结构篇——图

虽然树很灵活,并且有很多不同的应用,但是树本身存在局限,树只能表示层次关系。图是树的推广,在这一数据结构中不存在那么多的限制。图是由节点和顶点间的关系组成的集合。图是一种多用途的数据结构,可以表示多种情况。

简单的图G = (V,E)由非空顶点集V和边集合E组成。每条边都是V中两个定点的集合。顶点和边的数量分别用 |V| 和 |E| 表示。无向图中,边的形式为{Vij,Vji},且{Vji,Vij}={Vij,Vji},有向图中这种关系则不成立。一般情况下,我们记两个顶点之间的边为edge(Vi,Vj)。

如果每条边都附带有数值,则称之为加权图。如果任意两个顶点之间都有一条边将其连接起来,则称之为完全图。

图的邻接矩阵法表示 ,:如果存在边edge(Vi,Vj),则aij = 1(有向图中等于权值);否则aij = 0。如下图所示

图的遍历

和树的遍历相同,图的遍历操作也是对图中的每个节点只访问一次。简单的树的遍历算法不能应用在图上,因为图可能会包含循环,直接使用树的遍历算法就很有可能进入死循环。为了防止死循环,可以给已访问过的节点做一个标记,避免重复访问。

图的深度优先查找,先访问顶点V,再访问与顶点V邻接的未访问顶点。如果顶点V没有邻接顶点或者为访问过的顶点,则回溯到顶点V的前驱节点。如果回到了遍历开始的第一个顶点,则遍历结束。
除此之外,图也有相应的广度优先搜索,同样也需要添加检验节点是否被访问过的操作。

图的python实现

from collections import deque


class Graph(object):
    def __init__(self):
        self.order = []
        self.neighbor = {}

    def add_node(self, node):
        key, val = node
        if not isinstance(val, list):
            print('node value should be a list')

        self.neighbor[key] = val

    def bfs(self, root):
        if root != None:
            search_queue = deque()
            search_queue.append(root)
            visited = []
        else:
            print('root is None')
            return -1

        while search_queue:
            person = search_queue.popleft()
            self.order.append(person)

            if (not person in visited) and (person in self.neighbor.keys()):
                search_queue += self.neighbor[person]
                visited.append(person)

    def dfs(self, root):
        if root != None:
            search_queue = deque()
            search_queue.append(root)
            visited = []
        else:
            print('root is None')
            return -1

        while search_queue:
            person = search_queue.popleft()
            self.order.append(person)

            if (not person in visited) and (person in self.neighbor.keys()):
                tmp = self.neighbor[person]
                tmp.reverse()

                for index in tmp:
                    search_queue.appendleft(index)

                visited.append(person)

    def clear(self):
        self.order = []

    def node_print(self):
        for index in self.order:
            print(index, end='  ')

欢迎关注公众号 : 数学算法实验室
算法与人工智能

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章