def BFS(G,root,direction='forward'): """ Calculate BFS distances and predecessor without showing animations. If G is directed, direction does matter: - 'forward' BFS will use outgoing edges - 'backward' BFS will use incoming edges It uses gInfinity (from GatoGlobals.py) as infinite distance. returns (dist,pred) """ Q = Queue() d = {} pred = {} for v in G.vertices: d[v] = gInfinity d[root] = 0 pred[root] = root Q.Append(root) while Q.IsNotEmpty(): v = Q.Top() if G.QDirected() == 1 and direction == 'backward': nbh = G.InNeighbors(v) else: nbh = G.Neighborhood(v) for w in nbh: if d[w] == gInfinity: d[w] = d[v] + 1 pred[w] = v Q.Append(w) return (d,pred)
def FindBipartitePartitions(G): """ Finds the two partitions of a bipartite graph G and returns two vertex sets. If G is not bipartite, it returns two empty sets. """ Q = Queue() V = set() W = set() dist = {} for v in G.vertices: if v not in dist: dist[v] = 0 Q.Append(v) V.add(v) while Q.IsNotEmpty(): v = Q.Top() for w in G.Neighborhood(v): if w not in dist: dist[w] = dist[v] + 1 Q.Append(w) if dist[w] % 2 == 1: W.add(w) else: V.add(w) else: if (dist[w] + dist[v]) % 2 == 0: # Found an incompatible edge return (set(), set()) return (V, W)
def ConnectedComponents(G): """ Compute the connected components of the undirected graph G. Returns a list of lists of vertices. """ result = [] visited = {} for v in G.vertices: visited[v] = None for root in G.vertices: if visited[root] is not None: continue else: # Found a new component component = [root] visited[root] = 1 Q = Queue() Q.Append(root) while Q.IsNotEmpty(): v = Q.Top() nbh = G.Neighborhood(v) for w in nbh: if visited[w] == None: visited[w] = 1 Q.Append(w) component.append(w) result.append(component) return result
def RadialTreeBFS(G,root,direction='forward'): """ Calculate BFS distances and predecessor without showing animations. Also compute angles for a radial layout If G is directed, direction does matter: - 'forward' BFS will use outgoing edges - 'backward' BFS will use incoming edges It uses gInfinity (from GatoGlobals.py) as infinite distance. returns (dist,pred) """ Q = Queue() d = {} pred = {} angle = {} childrenrange = {} for v in G.vertices: d[v] = gInfinity d[root] = 0 pred[root] = None angle[root] = 0 childrenrange[root] = (0, 2 * pi) Q.Append(root) while Q.IsNotEmpty(): v = Q.Top() if G.QDirected() == 1 and direction == 'backward': nbh = G.InNeighbors(v) else: nbh = G.Neighborhood(v) # Compute size of unseen Nbh unseen = 0 for w in nbh: if d[w] == gInfinity: unseen += 1 if unseen > 0: range = childrenrange[v][1] - childrenrange[v][0] delta = range / float(unseen) delta2 = delta * 0.5 left = childrenrange[v][0] + delta2 for w in nbh: if d[w] == gInfinity: angle[w] = left + delta2 childrenrange[w] = (left,left+delta) left += delta d[w] = d[v] + 1 #print (v,w), "angle = ", angle[w]," range = ", childrenrange[w] Q.Append(w) return (d,pred,angle)
def Append(self, v): Queue.Append(self, v) self.Animator.SetVertexColor(v, self.ColorOn)