Solution Review 3: Topological Sorting of a Graph
This review provides a detailed analysis of the solution to topologically sort a graph.
We'll cover the following...
Solution: Using Recursion
Python 3.5
Files
import graph as gdef helperFunction(myGraph, currentNode, visited, result) :visited[currentNode] = True # Mark the current node as visited# Recur for all the adjacent vertices of currentNodefor i in myGraph.graph[currentNode] :if visited[i] == False :helperFunction(myGraph, i, visited, result)result.insert(0, currentNode) # Push current vertex to resultdef topologicalSort(myGraph) :visited = [False] * myGraph.vertices # Mark all the vertices as not visitedresult = [] # Our stack to store the result/outputfor currentNode in range(myGraph.vertices) :if visited[currentNode] == False :helperFunction(myGraph, currentNode, visited, result)return(result)# Driver code# Create a graph given in the above diagrammyGraph = g.Graph(5)myGraph.addEdge(0, 1)myGraph.addEdge(0, 3)myGraph.addEdge(1, 2)myGraph.addEdge(2, 3)myGraph.addEdge(2, 4)myGraph.addEdge(3, 4)print("Topological Sort")print(topologicalSort(myGraph))
Explanation
We traverse the given ...