You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We can use it to know which node comes after which or detect cycles.
43
+
The algorithm is easy to understand.
44
+
First, we build the adjacent list and count all the inbound of the node.
45
+
Then we start from the node whose inbound count is 0, adding it in to the `q_next`.
46
+
For every node we pop out from q_next
47
+
* We remove the node's outbound by decrease 1 on all its neighbor's inbound.
48
+
* Put the node's neighbor to `q_next` if it has no inbound
49
+
* Put the node into the `q`
50
+
Repeat the process until there is no more node.
51
+
The order in the `q` is the order we are going to encounter when we run through the directed graph.
52
+
If we cannot sort all the nodes in the graph, it means that there are some nodes we couldn't find its starting point, in other words, there are cycles in the graph.
53
+
54
+
Time: O(E+2V) ~= O(E+V)
55
+
we used O(E) to build the graph #[1], O(V) to find the starting point #[2], then traverse all the nodes again #[3].
56
+
Space: O(E+3V) ~= O(E+V), O(E+V) for the adjacent list. O(V) for the `q`, O(V) for the `q_next`.
0 commit comments