Implementation 2
Implementation 2
The Idea: Begin with two hash tables. One to represent the graph, and a second one to represent the inverse of a graph. This just creates a separate graph with the edges swapped.The reason for this will become clear later on. Next, we instantiate a queue
. This queue is always going to contain nodes that currently have no prerequisites. Instantiate the queue with all node(s) that have no dependances in the original graph g
. Next initiate a BFS. The front of the queue is always going to contain a node that has no prerequisites, so append it to the solution array. Following that, the associated prerequisites must be removed. Previously, implementation 1 iterated through the entirety of the graph, and so this scaled the complexity of our model by n
. Instead, iterate through all the associated edges of the removed node. This can be found within the inverse graph. As the elements become removed, we know that they also our only option for a potentially new independent node because initially the array was scanned for nodes without prerequisites and were placed into the queue. An acyclic graph will always reveal a topological ordering, so we can expect that our solution vector to contain the number of orderings as the original number number of nodes n
.
Complexity: O(|V|+|E|) time and O(|V|) space
Note: The input prerequisites is a graph represented by a list of edges, not adjacency matrices.
Last updated
Was this helpful?