Graph 和 Vertex 构建基于邻接列表:

# -*- coding: utf-8 -*-
# @Date   : 2019/12/1
# @File   : AdjListGraph.pyimport sysclass Vertex(object):def __init__(self, node):self.id = nodeself.adjacent = {} # 存该节点的邻居及其边权重self.distance = sys.maxsizeself.visited = Falseself.previous = Nonedef addNeighbor(self, neighbor, weight=0):self.adjacent[neighbor] = weightdef getConnections(self):return self.adjacent.keys()def getVertexID(self):return self.iddef setVertexID(self, id):self.id = iddef getWeight(self, neighbor):return self.adjacent.get(neighbor)def setDistance(self, dist):self.distance = distdef getDistance(self):return self.distancedef setPrevious(self, prev):self.previous = prevdef setVisited(self):self.visited = True# 打印节点时显示的信息def __str__(self):return str(self.id) + " adjacent: " + str([x.id for x in self.adjacent])def __lt__(self, other):return self.distance < other.distance and self.id < other.idclass Graph(object):def __init__(self, directed=False):self.vertexDict = {} # key:id  value:Vertex(id)self.numVertices = 0self.directed = directeddef __iter__(self):return iter(self.vertexDict.values())def isDirected(self):return self.directeddef vertexCount(self):return self.numVerticesdef addVertex(self, node):self.numVertices = self.numVertices + 1newVertex = Vertex(node)self.vertexDict[node] = newVertexreturn newVertexdef getVertex(self, n):return self.vertexDict.get(n)def addEdge(self, frm, to, cost=0):if frm not in self.vertexDict:self.addVertex(frm)if to not in self.vertexDict:self.addVertex(to)self.vertexDict[frm].addNeighbor(self.vertexDict[to], cost)if not self.directed:self.vertexDict[to].addNeighbor(self.vertexDict[frm], cost)def getVertices(self):# return idsreturn self.vertexDict.keys()# def setPrevious(self, current):#     self.previous = current## def getPrevious(self, current):#     return self.previousdef getEdges(self):edges = []for key, currentVertex in self.vertexDict.items():for neighbor in currentVertex.getConnections():currentVertexID = currentVertex.getVertexID()neighborID = neighbor.getVertexID()edges.append((currentVertexID, neighborID, currentVertex.getWeight(neighbor)))return edgesdef getNeighbors(self, v):vertex = self.vertexDict[v]return vertex.getConnections()if __name__ == '__main__':G = Graph(True)G.addVertex('a')G.addVertex('b')G.addVertex('c')G.addVertex('d')G.addVertex('e')G.addVertex('f')G.addEdge('a', 'b', 1)G.addEdge('a', 'c', 1)G.addEdge('b', 'd', 1)G.addEdge('b', 'e', 1)G.addEdge('c', 'd', 1)G.addEdge('c', 'e', 1)G.addEdge('d', 'e', 1)G.addEdge('e', 'a', 1)print(G.getEdges())for k in G.getEdges():print(k)print()for key in G.vertexDict:# 对应 Vertex中的__str__print(key, 'corresponds to', G.vertexDict[key])print()v = 'a'neighbors = G.getNeighbors(v)for n in neighbors:print(n)# 基于边的结合构建图def graphFromEdgeList(E, directed=False):"""Make a graph instance based on a sequence of edge tuples.Edges can be either of from (origin,destination) or(origin,destination,element). Vertex set is presume to be thoseincident to at least one edge.vertex labels are assumed to be hashable."""g = Graph(directed)# 得到所有节点名称V = set()for e in E:V.add(e[0])V.add(e[1])print("Vertex :", V)# 构建图节点vertexvertices = {}for v in V:vertices[v] = g.addVertex(v)print(g.vertexCount())# 根据边集合为节点添加边for e in E:src = e[0]dest = e[1]cost = e[2] if len(e) > 2 else Noneg.addEdge(src, dest, cost)return gE2 = (('A', 'B', 1), ('A', 'C', 1),)graph = graphFromEdgeList(E2, True)for k in graph.getEdges():print(k)print()E = (('SFO', 'LAX', 337), ('SFO', 'BOS', 2704), ('SFO', 'ORD', 1846),('SFO', 'DFW', 1464), ('LAX', 'DFW', 1235), ('LAX', 'MIA', 2342),('DFW', 'ORD', 802), ('DFW', 'MIA', 1121), ('ORD', 'BOS', 867),('ORD', 'JFK', 740), ('MIA', 'JFK', 1090), ('MIA', 'BOS', 1258),('JFK', 'BOS', 187),)graph = graphFromEdgeList(E, True)for e in graph.getEdges():print(e)for m in graph.getVertices():print(m)

DFS:

# -*- coding: utf-8 -*-
# @Date   : 2019/12/1
# @File   : DepthFirstSearch.pyfrom AdjListGraph import Graph, Vertexdef __dfsHelper(s, G, visited, parents):# if s == G:#     returnif s not in visited:visited[s.getVertexID()] = Trueprint("traversal: ", s.getVertexID())for neighbor in s.getConnections():if neighbor.getVertexID() not in visited:parents[neighbor.getVertexID()] = s.getVertexID()__dfsHelper(neighbor, G, visited, parents)# print(parents)def DFSRecursive(G):visited = {}parents = {}for node in G:if node.getVertexID() not in visited:__dfsHelper(node, G, visited, parents)print(visited)print(parents)def DFSIterative(G, start, dest):stack = []parents = {}visited = set()stack.append(start)while stack:node = stack.pop()print("traversal: ", node.getVertexID())if node.getVertexID() == dest.getVertexID():return parents# if node not in visited:visited.add(node.getVertexID())for neighbor in G.getNeighbors(node.getVertexID()):if neighbor not in visited:stack.append(neighbor)parents[neighbor.getVertexID()] = node.getVertexID()return Noneif __name__ == '__main__':G = Graph(directed=True)G.addVertex('a')G.addVertex('b')G.addVertex('c')G.addVertex('d')G.addVertex('e')G.addVertex('f')G.addEdge('a', 'b', 1)G.addEdge('a', 'c', 1)G.addEdge('b', 'd', 1)G.addEdge('b', 'e', 1)G.addEdge('c', 'd', 1)G.addEdge('c', 'e', 1)G.addEdge('d', 'e', 1)G.addEdge('e', 'a', 1)G.addEdge('a', 'f', 1)print(G.getEdges())for k in G.getEdges():print(k)visited = {}parents = {}DFSRecursive(G)print()# 从v节点开始遍历v = G.getVertex('e')__dfsHelper(v, G, visited, parents)#print("#"*20)start = G.getVertex('a')dest = G.getVertex('e')print(DFSIterative(G, start=start, dest=dest))

BFS:

# -*- coding: utf-8 -*-
# @Date   : 2019/12/1
# @File   : BreadthFirstSearch.pyfrom AdjListGraph import Graph
from collections import dequedef BFSIterative(G, start, dest):queue = deque()visited = set()parents = {}queue.append(start)while queue:node = queue.popleft()print("visiting :", node.getVertexID())if node.getVertexID() == dest.getVertexID():return parentsvisited.add(node.getVertexID())for neighbor in G.getNeighbors(node.getVertexID()):if neighbor not in visited:queue.append(neighbor)parents[neighbor.getVertexID()] = node.getVertexID()return Noneif __name__ == '__main__':G = Graph(directed=True)G.addVertex('a')G.addVertex('b')G.addVertex('c')G.addVertex('d')G.addVertex('e')G.addVertex('f')G.addEdge('a', 'b', 1)G.addEdge('a', 'c', 1)G.addEdge('a', 'f', 1)G.addEdge('b', 'd', 1)G.addEdge('b', 'e', 1)G.addEdge('c', 'd', 1)G.addEdge('c', 'e', 1)G.addEdge('d', 'e', 1)G.addEdge('e', 'a', 1)print(G.getEdges())for k in G.getEdges():print(k)#print("#" * 20)start = G.getVertex('a')dest = G.getVertex('e')print(BFSIterative(G, start=start, dest=dest))

DFS vs BFS:

【python3数据结构】图Graph及DFS(深度优先搜索)BFS(广度优先搜索)相关推荐

  1. DFS深度优先搜索算法/BFS广度优先搜索算法(c/c++)

    深度优先搜索算法(DFS) 深度优先搜索算法思路:(有点贪心算法的意思) 1,从某个给定结点a出发,访问它 2,查找关于a的邻接点,查找到a的第一个邻接点b之后,对b结点进行DFS搜索,也就是对b结点 ...

  2. 数据结构--图(Graph)详解(二)

    数据结构–图(Graph)详解(二) 文章目录 数据结构--图(Graph)详解(二) 一.图的存储结构 1.图的顺序存储法 2.图的邻接表存储法 3.图的十字链表存储法 4.图的邻接多重表存储法 二 ...

  3. 数据结构学习笔记——图的遍历算法(深度优先搜索和广度优先搜索)

    目录 一.图的遍历概念 二.深度优先搜索(DFS) (一)DFS算法步骤 1.邻接表DFS算法步骤 2.邻接矩阵DFS算法步骤 (二)深度优先生成树.森林 (三)DFS的空间复杂度和时间复杂度 三.广 ...

  4. a - 数据结构实验之图论一:基于邻接矩阵的广度优先搜索遍历_数据结构--图

    故事凌 今天 基本知识点 图可说是所有数据结构里面知识点最丰富的一个, 自己笨的知识点如下: 阶(oRDER), 度: 出度(out-Degree), 入度(in-Degree) 树(Tree), 森 ...

  5. 数据结构--图(Graph)详解(三)

    数据结构–图(Graph)详解(三) 文章目录 数据结构--图(Graph)详解(三) 一.深度优先生成树和广度优先生成树 1.铺垫 2.非连通图的生成森林 3.深度优先生成森林 4.广度优先生成森林 ...

  6. 数据结构--图(Graph)详解(一)

    数据结构–图(Graph)详解(一) 文章目录 数据结构--图(Graph)详解(一) 一.图的基本概念 1.图的分类 2.弧头和弧尾 3.入度和出度 4.(V1,V2) 和 < V1,V2 & ...

  7. 深度优先遍历和广度优先遍历_图与深度优先搜索和广度优先搜索

    什么是图? 图是一种复杂的非线性表结构.由若干给定的点一级任意两点间的连线所构成.图通常用来描述事物之间的特定关系, 代表的就是事物, 线就是事物之间所具有的关系.例如社交网络就是一种典型的图关系, ...

  8. 数据结构--图(Graph)详解(四)

    数据结构–图(Graph)详解(四) 文章目录 数据结构--图(Graph)详解(四) 一.图中几个NB的算法 1.普里姆算法(Prim算法)求最小生成树 2.克鲁斯卡尔算法(Kruskal算法)求最 ...

  9. 八数码深度优先搜索_深度优先搜索和广度优先搜索

    深度优先搜索和广度优先搜索 关于搜索&遍历 对于搜索来说,我们绝大多数情况下处理的都是叫 "所谓的暴力搜索" ,或者是说比较简单朴素的搜索,也就是说你在搜索的时候没有任何所 ...

  10. 算法十——深度优先搜索和广度优先搜索

    文章出处:极客时间<数据结构和算法之美>-作者:王争.该系列文章是本人的学习笔记. 搜索算法 算法是作用于数据结构之上的.深度优先搜索.广度优先搜索是作用于图这种数据结构之上的.图上的搜索 ...

最新文章

  1. Socket简介及客户端服务器连接实例
  2. 设计模式-观察者模式(Observer)
  3. 当Java枚举遇到位掩码,还能这么玩?
  4. lb开金矿 QDUOJ 数论
  5. 友情链接监控软件报表
  6. 单片机死机了怎么办?
  7. Flutter 本地数据库sqflite实战操作
  8. python将图片转为矢量图
  9. mysql列名命名_重命名MySQL中的列名?
  10. 数字未来,NFT未来,Game Farmer创始人胡烜峰在IGS上讲述FoxNFT和他的故事
  11. 去掉串口硬盘的安全删除硬件图标
  12. springboot配置内存数据库H2
  13. Lettuce: Connection to x.x.x.x not allowed. This connection point is not known in the cluster view
  14. 2020高交会第二十二届中国国际高新技术成果交易会
  15. 【Leetcode刷题Python】714. 买卖股票的最佳时机含手续费
  16. 你知道如何使用Java将DWG / DXF CAD文件转换为图像格式吗?
  17. 一个人对家的态度藏着最真实的人品
  18. distinct (去重)
  19. 苹果m1 ruby linner问题
  20. Linux 嵌入式开发 网络编程: day4

热门文章

  1. python打印楼梯和笑脸_用Python的Turtle库打印楼梯,并打印笑脸:)
  2. 英语对计算机的重要性,英语对计算机专业的重要性及如何提高英语水平
  3. Mask RCNN代码
  4. 踩坑:阿里云oss上传图片报空指针异常
  5. 数字逻辑:模60计数器(使用MAX+plus II 、Verilog语言 编写)
  6. Tomcat8性能JVM优化
  7. Java学习-IO流-read()和write()详解
  8. 5线制jlink仿真接线的方法
  9. 在微信小程序中打开地图选择位置功能
  10. linux设置屏保时间命令,Linux下屏保设置