# -*- coding: utf-8 -*- import re from repo import SparseGraph, DenseGraph #由于我们只需要定义一个函数就可以把数据生成图,所以就不定义成类了 #并且文件中第一行顶点的数量和边的数量我删掉了,对python来说没意义。 #此函数仅适用于无权图,改良版见第八章 def buildGraphFromFile(aGraph, filePath): graphList = [] with open(filePath, 'r', encoding='utf-8') as f: for line in f: graphList.append([int(x) for x in re.split(r'\s+', line.strip())]) for i in range(len(graphList)): aGraph.addEdge(graphList[i][0], graphList[i][1]) ''' g1=DenseGraph(13) #必须填入正确的结点个数。。。我真的觉得邻接矩阵不好用 buildGraphFromFile(g1,'testG1.txt') print(g1) ''' g2 = SparseGraph() buildGraphFromFile(g2, 'testG2.txt') g2.getAllInfo()
assert w >= 0 and w < len(self.graph.vertDict) return self.graph.vertDict[w].visited() def shortestPath(self, w): assert w >= 0 and w < len(self.graph.vertDict) if not self.hasPathTo(w): return print('There is no path between %s and %s' % (self.startVert.getId(), w)) pathlist = [w] currentVert = self.graph.vertDict[w] while currentVert != self.startVert: currentVert = currentVert.getPred() pathlist.append(currentVert.getId()) pathlist.reverse() return pathlist def showPath(self, w): assert w >= 0 and w < len(self.graph.vertDict) pathlist = self.shortestPath(w) print(pathlist) g = SparseGraph(directed=True, weighted=True) buildGraphFromFile(g, 'testG2.txt') S = Spfa(g, 0) print(S.shortestPathTo(4)) S.showPath(4) ''' 对于spfa算法来说,检测是否有负权环的方法是:同一个节点进入队列的次数超过N次(N-1次?)。 这里我偷懒了,没有对图的负权环进行检测,所以不要传入带负权环的图去测试。 '''
nextVertex.setPred(startVertex) self._dfs(nextVertex) def hasPath(self, w): return self.graph.vertDict[w].visited() def path(self, w): #老师三个函数里没有将具体路径返回的函数,我认为是有必要的,所以我让path函数返回了pathlist if not self.hasPath(w): return print('There is no path between %s and %s' % (self.startVertex.getId(), w)) self.pathlist = [w] currentVertex = self.graph.vertDict[w] while currentVertex != self.startVertex: currentVertex = currentVertex.getPred() self.pathlist.append(currentVertex.getId()) self.pathlist.reverse() return self.pathlist def showPath(self, w): self.pathlist = [] self.path(w) if self.pathlist: print(self.pathlist) graph = SparseGraph(directed=True) buildGraphFromFile(graph, 'testG2.txt') path = SearchPath(graph, 3) path.showPath(5) path.showPath(4)
'%s-%s' % (nextVert.getId(), currentVert.getId()))) self.edgesList.sort() def spanTree(self): self._getEdges() uf = UnionFind(self.graph.getVertNum()) for tuple in self.edgesList: if len(self.edgesOfTree) == self.graph.getVertNum(): break v1, v2 = [int(i) for i in re.split('\D+', tuple[1])] if not uf.isConnected(v1, v2): uf.Union(v1, v2) self.edgesOfTree.append(tuple) def result(self): totalWeight = 0 for tuple in self.edgesOfTree: totalWeight += tuple[0] return totalWeight def edges(self): for tuple in self.edgesOfTree: print('%s : %s' % (tuple[1], tuple[0])) g = SparseGraph(weighted=True) buildGraphFromFile(g, 'testG1.txt') k = Kruskal(g) k.edges() print(k.result())
vertex.setVisited(True) vertex.setPred(currentVertex) queue.enqueue(vertex) def hasPath(self, w): assert w >= 0 and w < len(self.graph.vertDict) return self.graph.vertDict[w].visited() def path(self, w): assert w >= 0 and w < len(self.graph.vertDict) if not self.hasPath(w): return print('There is no path between %s and %s' % (self.startVertex.getId(), w)) pathlist = [w] currentVertex = self.graph.vertDict[w] while currentVertex != self.startVertex: currentVertex = currentVertex.getPred() pathlist.append(currentVertex.getId()) pathlist.reverse() return pathlist def showPath(self, w): assert w >= 0 and w < len(self.graph.vertDict) pathlist = self.path(w) print(pathlist) graph = SparseGraph() buildGraphFromFile(graph, 'testG2.txt') sp = ShortestPath(graph, 0) sp.showPath(3)
class ComponentsCounter(object): def __init__(self, aGraph): self.graph = aGraph self.result = 0 self.calc() def calc(self): #result store in both graph.ccount and self.result for vertex in self.graph: vertex.setVisited(False) for vertex in self.graph: if not vertex.visited(): self._dfs(vertex, self.graph.getCcount()) self.graph.setCcount(self.graph.getCcount() + 1) self.result += 1 def _dfs(self, startVertex, ccount): startVertex.setCCID(ccount) startVertex.setVisited(True) for nextVertex in startVertex.getConnections(): if not nextVertex.visited(): self._dfs(nextVertex, ccount) def getResult(self): return self.result graph = SparseGraph() buildGraphFromFile(graph, 'testG1.txt') Counter = ComponentsCounter(graph) print(Counter.getResult()) print(graph.isConnected(0, 5))
# -*- coding: utf-8 -*- import re from repo import SparseGraph #此函数兼容有权图与无权图 def buildGraphFromFile(aGraph, filePath): graphList = [] hasWeight = False with open(filePath, 'r', encoding='utf-8') as f: for line in f: graphList.append( [float(x) for x in re.split(r'\s+', line.strip())]) if len(graphList[0]) > 2: hasWeight = True for i in range(len(graphList)): if hasWeight: aGraph.addEdge(int(graphList[i][0]), int(graphList[i][1]), graphList[i][2]) else: aGraph.addEdge(int(graphList[i][0]), int(graphList[i][1])) g = SparseGraph(weighted=True) buildGraphFromFile(g, 'testG1.txt') g.getAllInfo()