Data Structures and Algorithm Analysis

图的 python实现

2019-03-27  本文已影响0人  盗梦者_56f2

介绍

图(Graph)是一种网状数据结构,其形式化定义如下:
Graph=(V, R)
V={X | X属于DataObject}
R={VR}
VR={<x, y> | P(x, y) ^ (x, y属于V)}
DataObject为一个集合,该集合中所有的元素具有相同的特性。V中的数据元素通常称为顶点,VR是两个顶点之间的关系的集合。P(x, y)表示x和y之间有特定的关联属性P。
若<x, y>属于VR,则<x, y>表示从顶点x到顶点y的一条弧(arc),并称x为弧尾(tail)或起始点,称y为弧头(head)或终端店,此时图中的边是有方向的,称这样的图为有向图。
<x, y>属于VR,必有<y,x>属于VR,及VR是对称关系,这时以无序对(x,y)来代替两个有序对,表示x和y之间的一条边(edge),此时的图称为无向图。

python

class Graph(object):
    def __init__(self, gdict=None):
        if gdict is None:
            gdict = {}
        self.gdict = gdict

    def getVertices(self):
        '''
        得到图的所有顶点
        :return:
        '''
        return list(self.gdict.keys())

    def addVertex(self, vrtx):
        '''
        添加一个顶点
        :param vrtx:
        :return:
        '''
        if vrtx not in self.gdict:
            self.gdict[vrtx] = {}

    def addEdge(self, edge):
        '''
        添加一个边
        :param edge:
        :return:
        '''
        edge = set(edge)
        (vrtx1, vrtx2) = tuple(edge)
        if vrtx1 in self.gdict:
            self.gdict[vrtx1].add(vrtx2)
        else:
            self.gdict[vrtx1] = {vrtx2, }

    def findEdge(self):
        '''
        打印所有的边
        :return:
        '''
        edgename = []
        for vrtx in self.gdict:
            for nxtvrtx in self.gdict[vrtx]:
                if {nxtvrtx, vrtx} not in edgename:
                    edgename.append({vrtx, nxtvrtx})
        return edgename

    def dfs(self, node, visited=None):
        '''
        深度优先遍历
        :param node:
        :param visited:
        :return:
        '''
        if visited is None:
            visited = set()
        visited.add(node)
        print(node)
        for next in self.gdict[node] - visited:
            self.dfs(next, visited)
        return visited

    def bfs(self, node):
        '''
        广度优先遍历
        :param node:
        :return:
        '''
        seen = set([node])
        queue = collections.deque([node])
        while queue:
            vertex = queue.popleft()
            print(vertex)
            for next in self.gdict[vertex]:
                if next not in seen:
                    seen.add(next)
                    queue.append(next)


graph_elements = {"a": {"b", "c"},
                  "b": {"a", "d"},
                  "c": {"a", "d"},
                  "d": {"e", },
                  "e": {"d", }
                  }
g = Graph(graph_elements)
print(g.getVertices())
上一篇下一篇

猜你喜欢

热点阅读