A collection of generally used Graph Algorithms in one place with simple constructs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 | # Graph Algorithms using basic python Constructs.
# Narayana Chikkam, Dec, 22, 2015.
from collections import defaultdict
from heapq import *
import itertools
import copy
from lib.unionfind import (
UnionFind
)
from lib.prioritydict import (
priorityDictionary
)
class Vertex:
def __init__(self, id):
self.id = id
self.neighbours = {}
def addNeighbour(self, id, weight):
self.neighbours[id] = weight
def __str__(self):
return str(self.id) + ': ' + str(self.neighbours.keys())
def getNeighbours(self):
return self.neighbours #.keys()
def getName(self):
return self.id
def getWeight(self, id):
return self.neighbours[id]
class Graph:
def __init__(self):
self.v = {}
self.count = 0
def addVertex(self, key):
self.count += 1
newV = Vertex(key)
self.v[key] = newV
def getVertex(self, id):
if id in self.v.keys():
return self.v[id]
return None
def __contains__(self, id):
return id in self.v.keys()
def addEdge(self, vertexOne, vertexTwo, weight=None): # vertexOne, vertexTwo, cost-of-the-edge
if vertexOne not in self.v.keys():
self.addVertex(vertexOne)
if vertexTwo not in self.v.keys():
self.addVertex(vertexTwo)
self.v[vertexOne].addNeighbour(vertexTwo, weight)
def updateEdge(self, vertexOne, vertexTwo, weight=None): # vertexOne, vertexTwo, cost-of-the-edge
self.v[vertexOne].addNeighbour(vertexTwo, weight)
def getVertices(self):
return self.v.keys()
def __str__(self):
ret = "{ "
for v in self.v.keys():
ret += str(self.v[v].__str__()) + ", "
return ret + " }"
def __iter__(self):
return iter(self.v.values())
def getNeighbours(self, vertex):
if vertex not in self.v.keys():
raise "Node %s not in graph" % vertex
return self.v[vertex].neighbours #.keys()
def getEdges(self):
edges = []
for node in self.v.keys():
neighbours = self.v[node].getNeighbours()
for w in neighbours:
edges.append((node, w, neighbours[w])) #tuple, srcVertex, dstVertex, weightBetween
return edges
def findIsolated(self):
isolated = []
for node in self.v:
deadNode = False
reachable = True
# dead node, can't reach any other node from this
if len(self.v[node].getNeighbours()) == 0:
deadNode = True
# reachable from other nodes ?
nbrs = [n.neighbours.keys() for n in self.v.values()]
# flatten the nested list
nbrs = list(itertools.chain(*nbrs))
if node not in nbrs:
reachable = False
if deadNode == True and reachable == False:
isolated.append(node)
return isolated
def getPath(self, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in self.v:
return None
for vertex in self.v[start].getNeighbours():
if vertex not in path:
extended_path = self.getPath(vertex,
end,
path)
if extended_path:
return extended_path
return None
def getAllPaths(self, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in self.v:
return []
paths = []
for vertex in self.v[start].getNeighbours():
if vertex not in path:
extended_paths = self.getAllPaths(vertex,
end,
path)
for p in extended_paths:
paths.append(p)
return paths
def inDegree(self, vertex):
"""
how many edges coming into this vertex
"""
nbrs = [n.neighbours.keys() for n in self.v.values()]
# flatten the nested list
nbrs = list(itertools.chain(*nbrs))
return nbrs.count(vertex)
def outDegree(self, vertex):
"""
how many vertices are neighbours to this vertex
"""
adj_vertices = self.v[vertex].getNeighbours()
return len(adj_vertices)
"""
The degree of a vertex is the no of edges connecting to it.
loop is counted twice
for an undirected Graph deg(v) = indegree(v) + outdegree(v)
"""
def getDegree(self, vertex):
return self.inDegree(vertex) + self.outDegree(vertex)
def verifyDegreeSumFormula(self):
"""Handshaking lemma - Vdeg(v) = 2 |E| """
degSum = 0
for v in self.v:
degSum += self.getDegree(v)
return degSum == (2* len(self.getEdges()))
def delta(self):
""" the minimum degree of the Graph V """
min = 2**64
for vertex in self.v:
vertex_degree = self.getDegree(vertex)
if vertex_degree < min:
min = vertex_degree
return min
def Delta(self):
""" the maximum degree of the Graph V """
max = -2**64
for vertex in self.v:
vertex_degree = self.getDegree(vertex)
if vertex_degree > max:
max = vertex_degree
return max
def degreeSequence(self):
"""
degree sequence is the reverse sorder of the vertices degrees
Isomorphic graphs have the same degree sequence. However,
two graphs with the same degree sequence are not necessarily
isomorphic.
More-Info:
http://en.wikipedia.org/wiki/Graph_realization_problem
"""
seq = []
for vertex in self.v:
seq.append(self.getDegree(vertex))
seq.sort(reverse=True)
return tuple(seq)
# helper to check if the given sequence is in non-increasing Order ;)
@staticmethod
def sortedInDescendingOrder(seq):
return all (x>=y for x,y in zip(seq, seq[1:]))
@staticmethod
def isGraphicSequence(seq):
"""
Assumes that the degreeSequence is a list of non negative integers
http://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93Gallai_theorem
"""
# Check to ensure there are an even number of odd degrees
if sum(seq)%2 != 0: return False
# Erdos-Gallai theorem
for k in range(1, len(seq)+1):
leftSum = sum(seq[:(k)])
rightSum = k * (k-1) + sum([min(x, k) for x in seq[k:]])
if leftSum > rightSum: return False
return True
@staticmethod
def isGraphicSequenceIterative(s):
# successively reduce degree sequence by removing node of maximum degree
# as in Havel-Hakimi algorithm
while s:
s.sort() # sort in increasing order
if s[0]<0:
return False # check if removed too many from some node
d=s.pop() # pop largest degree
if d==0: return True # done! rest must be zero due to ordering
# degree must be <= number of available nodes
if d>len(s): return False
# remove edges to nodes of next higher degrees
#s.reverse() # to make it easy to get at higher degree nodes.
for i in range(len(s)-1,len(s)-(d+1),-1):
s[i]-=1
# should never get here b/c either d==0, d>len(s) or d<0 before s=[]
return False
def density(self):
"""
In mathematics, a dense graph is a graph in which the number of edges
is close to the maximal number of edges. The opposite, a graph with
only a few edges, is a sparse graph. The distinction between sparse
and dense graphs is rather vague, and depends on the context.
For undirected simple graphs, the graph density is defined as:
D = (2*No-Of-Edges)/((v*(v-1))/2)
For a complete Graph, the Density D is 1
"""
""" method to calculate the density of a graph """
V = len(self.v.keys())
E = len(self.getEdges())
return 2.0 * E / (V *(V - 1))
"""
Choose an arbitrary node x of the graph G as the starting point
Determine the set A of all the nodes which can be reached from x.
If A is equal to the set of nodes of G, the graph is connected; otherwise
it is disconnected.
"""
def isConnected(self, start=None):
if start == None:
start = self.v.keys()[0]
reachables = self.dfs(start, [])
return len(reachables) == len(self.v.keys())
"""
ToDo: USE CLR Approach for this Later
"""
def dfs(self, start, path = []):
path = path + [start]
for v in self.v[start].getNeighbours().keys():
if v not in path:
path = self.dfs(v, path)
return path
"""
CLR Sytle
"""
def CLR_Dfs(self):
paths = []
for v in self.v.keys():
explored = self.dfs(v, [])
if len(explored) == len(self.v.keys()):
paths.append(explored)
return paths
def BFS(self, start):
# initialize lists
maxV = len(self.v.keys())
processed = [False] * (maxV) # which vertices have been processed
discovered = [False] * (maxV) # which vertices have been found
parent= [-1] * (maxV) # discovery relation
q = [] # queue of vertices to visit */
# enqueue(&q,start);
q.append(start)
discovered[start] = True
while (len(q) != 0):
v = q.pop(0)
processed[v] = True
nbrs = self.v[v].getNeighbours().keys()
# print nbrs
for n in nbrs:
# if processed[n] == False
if discovered[n] == False:
q.append(n)
discovered[n] = True
parent[n] = v
return (discovered, parent)
def findPath(self, start, end, parents, path):
if ((start == end) or (end == -1)):
path.append(start)
else:
self.findPath(start, parents[end], parents, path)
path.append(end)
"""
Find path between two given nodes
"""
def find_path(self, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not self.v.has_key(start):
return None
for node in self.v[start].getNeighbours().keys():
if node not in path:
newpath = self.find_path(node, end, path)
if newpath: return newpath
return None
"""
Find all paths
"""
def find_all_paths(self, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not self.v.has_key(start):
return []
paths = []
for node in self.v[start].getNeighbours().keys():
if node not in path:
newpaths = self.find_all_paths(node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
"""
Find shorted path w.r.t no of vertices on the path
"""
def find_shortest_path(self, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not self.v.has_key(start):
return None
shortest = None
for node in self.v[start].getNeighbours().keys():
if node not in path:
newpath = self.find_shortest_path(node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
"""
prim's algorithm - properties: tree could be not connected during
the finding process as it finds edges with min cost - greedy strategy
Prims always stays as a tree
If you don't know all the weight on edges use
Prim's algorithm
f you only need partial solution on the graph
use Prim's algorithm
"""
def mspPrims(self):
nodes = self.v.keys()
edges = [(u, v, c) for u in self.v.keys() for v, c in self.v[u].getNeighbours().items()]
return self.prim(nodes, edges)
def prim(self, nodes, edges):
conn = defaultdict( list )
for n1,n2,c in edges: # makes graph undirected
conn[ n1 ].append( (c, n1, n2) )
conn[ n2 ].append( (c, n2, n1) )
mst = []
used = set()
used.add( nodes[0] )
usable_edges = conn[ nodes[0] ][:]
heapify( usable_edges )
while usable_edges:
cost, n1, n2 = heappop( usable_edges )
if n2 not in used:
used.add( n2 )
mst.append( ( n1, n2, cost ) )
for e in conn[ n2 ]:
if e[ 2 ] not in used:
heappush( usable_edges, e )
return mst
"""
Kruskals begins with forest and merge into a tree
"""
def mspKrushkals(self):
nodes = self.v.keys()
edges = [(c, u, v) for u in self.v.keys() for v, c in self.v[u].getNeighbours().items()]
return self.krushkal(edges)
def pprint(self):
print ("{ ", end=" ")
for u in self.v.keys():
print (u, end=" ")
print (": { ", end=" ")
for v in self.v[u].getNeighbours().keys():
print (v, ":", self.v[u].getNeighbours()[v], end=" ")
print(" }", end= " ")
print (" }\n")
def krushkal(self, edges):
"""
Return the minimum spanning tree of an undirected graph G.
G should be represented in such a way that iter(G) lists its
vertices, iter(G[u]) lists the neighbors of u, G[u][v] gives the
length of edge u,v, and G[u][v] should always equal G[v][u].
The tree is returned as a list of edges.
"""
# Kruskal's algorithm: sort edges by weight, and add them one at a time.
# We use Kruskal's algorithm, first because it is very simple to
# implement once UnionFind exists, and second, because the only slow
# part (the sort) is sped up by being built in to Python.
subtrees = UnionFind()
tree = []
for c,u,v in sorted(edges): # take from small weight to large in order
if subtrees[u] != subtrees[v]:
tree.append((u,v, c))
subtrees.union(u,v)
return tree
def adj(self, missing=float('inf')): # makes the adj dict will all possible cells, similar to matrix
"""
G= { 0 : { 1 : 6, 2 : 4 }
1 : { 2 : 3, 5 : 7 }
2 : { 3 : 9, 4 : 1 }
3 : { 4 : 1 }
4 : { 5 : 5, 6 : 2 }
5 : { }
6 : { }
}
adj(G) >>
{ 0: {0: 0, 1: 6, 2: 4, 3: inf, 4: inf, 5: inf, 6: inf},
1: {0: inf, 1: 0, 2: 3, 3: inf, 4: inf, 5: 7, 6: inf},
2: {0: inf, 1: inf, 2: 0, 3: 9, 4: 1, 5: inf, 6: inf},
3: {0: inf, 1: inf, 2: inf, 3: 0, 4: 1, 5: inf, 6: inf},
4: {0: inf, 1: inf, 2: inf, 3: inf, 4: 0, 5: 5, 6: 2},
5: {0: inf, 1: inf, 2: inf, 3: inf, 4: inf, 5: 0, 6: inf},
6: {0: inf, 1: inf, 2: inf, 3: inf, 4: inf, 5: inf, 6: 0}
}
"""
vertices = self.v.keys()
return {v1:
{v2: 0 if v1 == v2 else self.v[v1].getNeighbours().get(v2, missing) for v2 in vertices
}
for v1 in vertices
}
def floyds(self):
"""
All pair shortest Path
Idea:
for k in (0, n):
for i in (0, n):
for j in (0, n):
g[i][j] = min(graph[i][j], graph[i][k]+graph[k][j])
Find the shortest distance between every pair of vertices in the weighted Graph G
"""
d = self.adj() # prepare the adjacency list representation for the algorithm
vertices = self.v.keys()
for v2 in vertices:
d = {v1: {v3: min(d[v1][v3], d[v1][v2] + d[v2][v3])
for v3 in vertices}
for v1 in vertices}
return d
def reachability(self):
""" Idea: graph reachability floyd-warshall
for k in (0, n):
for i in (0, n):
for j in (0, n):
g[i][j] = graph[i][j] || (graph[i][k]&&graph[k][j]))
"""
vertices = self.v.keys()
d = self.adj(float('0'))
for u in vertices:
for v in vertices:
if u ==v or d[u][v]: d[u][v] = True
else: d[u][v] = False
for v2 in vertices:
d = {v1: {v3: d[v1][v3] or (d[v1][v2] and d[v2][v3]) # path for v1->v3 or v1->v2, v2-?v3
for v3 in vertices}
for v1 in vertices}
return d
def pathRecoveryFloydWarshall(self):
d = self.adj() # missing edges will have -1.0 value
vertices = self.v.keys()
parentMap = copy.deepcopy(d)
for v1 in vertices:
for v2 in vertices:
if (v1 == v2) or d[v1][v2] == float('inf'):
parentMap[v1][v2] = -1
else:
parentMap[v1][v2] = v1
for i in vertices:
for j in vertices:
for k in vertices:
temp = d[i][k] + d[k][j]
if temp < d[i][j]:
d[i][j] = temp
parentMap[i][j] = parentMap[k][j]
return parentMap
def getFloydPath(self, parentMap, u, v, path=[]):
"""
recursive procedure to get the path from parentMap matrix
"""
path.append(v)
if u != v and v != -1:
self.getFloydPath(parentMap, u, parentMap[u][v], path)
# from active recipes - handy thoughts to think about heap for this algorithm
def dijkstra(self, start, end=None):
"""
Find shortest paths from the start vertex to all
vertices nearer than or equal to the end.
The input graph G is assumed to have the following
representation: A vertex can be any object that can
be used as an index into a dictionary. G is a
dictionary, indexed by vertices. For any vertex v,
G[v] is itself a dictionary, indexed by the neighbors
of v. For any edge v->w, G[v][w] is the length of
the edge. This is related to the representation in
<http://www.python.org/doc/essays/graphs.html>
Of course, G and G[v] need not be Python dict objects;
they can be any other object that obeys dict protocol,
for instance a wrapper in which vertices are URLs
and a call to G[v] loads the web page and finds its links.
The output is a pair (D,P) where D[v] is the distance
from start to v and P[v] is the predecessor of v along
the shortest path from s to v.
Dijkstra's algorithm is only guaranteed to work correctly
when all edge lengths are positive. This code does not
verify this property for all edges (only the edges seen
before the end vertex is reached), but will correctly
compute shortest paths even for some graphs with negative
edges, and will raise an exception if it discovers that
a negative edge has caused it to make a mistake.
Introduction to Algorithms, 1st edition), page 528:
G = { 's':{'u':10, 'x':5},
' u':{'v':1, 'x':2},
'v':{'y':4},
'x':{'u':3, 'v':9, 'y':2},
'y':{'s':7, 'v':6}
}
"""
G = self.adj()
D = {} # dictionary of final distances
P = {} # dictionary of predecessors
Q = priorityDictionary() # est.dist. of non-final vert.
Q[start] = 0
for v in Q:
D[v] = Q[v]
if v == end: break
for w in G[v]:
vwLength = D[v] + G[v][w]
if w in D:
if vwLength < D[w]:
raise (ValueError, "Dijkstra: found better path to already-final vertex")
elif w not in Q or vwLength < Q[w]:
Q[w] = vwLength
P[w] = v
return D,P
def shortestPathDijkstra(self, start, end):
"""
Find a single shortest path from the given start vertex
to the given end vertex.
The input has the same conventions as Dijkstra().
The output is a list of the vertices in order along
the shortest path.
"""
D, P = self.dijkstra(start, end)
Path = []
while 1:
Path.append(end)
if end == start: break
end = P[end]
Path.reverse()
return Path
"""
smart snippet on the dijkstra alg:
def shortestPath(graph, start, end):
queue = [(0, start, [])]
seen = set()
while True:
(cost, v, path) = heapq.heappop(queue)
if v not in seen:
path = path + [v]
seen.add(v)
if v == end:
return cost, path
for (next, c) in graph[v].iteritems():
heapq.heappush(queue, (cost + c, next, path))
"""
def strongly_connected_components(self):
"""
Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a graph theory algorithm
for finding the strongly connected components of a graph.
Based on: http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
"""
index_counter = [0]
stack = []
lowlinks = {}
index = {}
result = []
def strongconnect(node):
# set the depth index for this node to the smallest unused index
index[node] = index_counter[0]
lowlinks[node] = index_counter[0]
index_counter[0] += 1
stack.append(node)
# Consider successors of `node`
try:
successors = self.v[node].getNeighbours().keys()
print(node, successors)
except:
successors = []
for successor in successors:
if successor not in lowlinks:
# Successor has not yet been visited; recurse on it
strongconnect(successor)
lowlinks[node] = min(lowlinks[node],lowlinks[successor])
elif successor in stack:
# the successor is in the stack and hence in the current strongly connected component (SCC)
lowlinks[node] = min(lowlinks[node],index[successor])
# If `node` is a root node, pop the stack and generate an SCC
if lowlinks[node] == index[node]:
connected_component = []
while True:
successor = stack.pop()
connected_component.append(successor)
if successor == node: break
component = tuple(connected_component)
# storing the result
print(component)
result.append(component)
for node in self.v.keys():
if node not in lowlinks:
strongconnect(node)
return result
def computeFirstUsingSCC(self, initFirst):
index_counter = [0]
stack = []
lowlinks = {}
index = {}
result = []
first = {}
def computeFirst(node):
# set the depth index for this node to the smallest unused index
index[node] = index_counter[0]
lowlinks[node] = index_counter[0]
index_counter[0] += 1
stack.append(node)
# Consider successors of `node`
try:
successors = self.v[node].getNeighbours().keys()
except:
successors = []
for successor in successors:
if successor not in lowlinks:
# Successor has not yet been visited; recurse on it
computeFirst(successor)
lowlinks[node] = min(lowlinks[node],lowlinks[successor])
elif successor in stack:
# the successor is in the stack and hence in the current strongly connected component (SCC)
lowlinks[node] = min(lowlinks[node],index[successor])
first[node] |= set(first[successor] - set(['epsilon'])).union(set(initFirst[node])) #(*union!*)
# If `node` is a root node, pop the stack and generate an SCC
if lowlinks[node] == index[node]:
connected_component = []
while True:
successor = stack.pop()
#FIRST[w] := FIRST[v]; (*distribute!*)
first[successor] = set(first[node] - set(['epsilon'])).union(set(initFirst[successor]) )#(*distribute!*)
connected_component.append(successor)
if successor == node: break
component = tuple(connected_component)
# storing the result
result.append(component)
for v in initFirst:
first[v] = initFirst[v] #(*init!*)
#print "init First assignment: ", first
for node in self.v.keys():
if node not in lowlinks:
computeFirst(node)
return first
def computeFollowUsingSCC(self, FIRST, initFollow):
index_counter = [0]
stack = []
lowlinks = {}
index = {}
result = []
follow = {}
def computeFollow(node):
# set the depth index for this node to the smallest unused index
index[node] = index_counter[0]
lowlinks[node] = index_counter[0]
index_counter[0] += 1
stack.append(node)
# Consider successors of `node`
try:
successors = self.v[node].getNeighbours().keys()
except:
successors = []
for successor in successors:
if successor not in lowlinks:
# Successor has not yet been visited; recurse on it
computeFollow(successor)
lowlinks[node] = min(lowlinks[node],lowlinks[successor])
elif successor in stack:
# the successor is in the stack and hence in the current strongly connected component (SCC)
lowlinks[node] = min(lowlinks[node],index[successor])
follow[node] |= follow[successor] #(*union!*)
# If `node` is a root node, pop the stack and generate an SCC
if lowlinks[node] == index[node]:
connected_component = []
while True:
successor = stack.pop()
follow[successor] = follow[node]
connected_component.append(successor)
if successor == node: break
component = tuple(connected_component)
# storing the result
result.append(component)
for v in initFollow:
follow[v] = initFollow[v] #(*init!*)
for node in self.v.keys():
if node not in lowlinks:
computeFollow(node)
return follow
|
Tags: graph