Lecture 4.7 - Topological Sorting
Lecture 4.7 - Topological Sorting
Madhavan Mukund
https://www.cmi.ac.in/~madhavan
5 6 7
Strategy
First list vertices with no 0 1
dependencies
As we proceed, list vertices whose
2
dependencies have already been listed
4
...
3
5 6 7
Strategy
First list vertices with no 0 1
dependencies
As we proceed, list vertices whose
2
dependencies have already been listed
4
...
3
Questions
Why will there be a starting vertex 5 6 7
with no dependencies?
How do we guarantee we can keep
progressing with the listing?
2
4
5 6 7
5 6 7
Fact
Every DAG has a vertex with indegree 0 0 1
0 1
2
4
3
5 6 7
2
2 1
4
1
3
2 1 4
5 6 7
for i in range(rows):
j = min([k for k in range(cols)
if indegree[k] == 0])
toposortlist.append(j)
indegree[j] = indegree[j]-1
for k in range(cols):
if AMat[j,k] == 1:
indegree[k] = indegree[k] - 1
return(toposortlist)
return(toposortlist)
return(toposortlist)
Complexity
Using adjacency matrix takes O(n2 )
Using adjacency list takes O(m + n)