BFS (Kahn’s Algorithm)
reference: https://www.geeksforgeeks.org/dsa/topological-sorting-indegree-based-solution/
example to check cycle
1 | 1 -> 2 -> 3 |
First, the indegree of each node is calculated:
- Node 1 has an indegree of 0 (no incoming edges).
- Node 2 has an indegree of 2 (one incoming edge from Node 1 and one from Node 3).
- Node 3 has an indegree of 1 (one incoming edge from Node 2).
So we start with Node 1 in the queue (indegree 0).
- dequeue Node 1, push it to result, and reduce the indegree of Node 2 by 1 (now indegree of Node 2 is 1).
- Now, the queue is empty
However, Node 2 still has an indegree of 1, and Node 3 has an indegree of 1. This means there are still nodes with incoming edges that haven’t been processed, indicating a cycle in the graph.
code
1 | from collections import deque |
DFS
If uses only one array to track visited nodes, when encouters cases like
1 | a b |
When starts DFS from b after finishing DFS from a, c has been marked as visited. However, this “visited” is not from the current round of DFS, which is not a cycle actually. Therefore, we need two arrays to track visited nodes: one for all visited nodes, and one for nodes visited in the current round of DFS.
1 | class Solution: |