Topological sort two ways on the same graph. Kahn's algorithm keeps a ready queue of nodes with nothing left blocking them; the DFS version pushes each node onto a finished stack once everything after it is done. Build a cycle and both show exactly where it breaks.
Emitted nodes turn green. If the queue runs dry early, whatever is left over gets a shaded outline: it sits inside a cycle, or depends on one.
Every node starts tagged with its in-degree: how many arrows point at it. shirt, trousers and socks already have nothing pointing at them, so they go straight into the ready queue.
Ordering tasks so every dependency comes before whatever needs it: build systems compiling files, package managers installing dependencies, spreadsheet formulas recalculating in the right order, and course prerequisite planning are all topological sorts in disguise.
Only when the graph is a DAG, a directed graph with no cycle. A cycle means A must come before B, which must come before A, and no linear order can satisfy both. Kahn's algorithm detects this for free: if it emits fewer nodes than the graph contains, whatever is left over is stuck in or behind a cycle.
Usually not. Whenever more than one node is ready at the same time, the algorithm has a real choice, and a different pick produces a different, equally valid order. A problem expecting one exact answer has to specify a tie-break, such as always taking the smallest available node.
BFS explores outward from one starting node and answers questions about distance. A topological sort has no single starting point: it processes the whole graph at once, tracking how many unmet dependencies each node has left, and a node only becomes eligible once every dependency ahead of it has already been placed.
A node's call cannot return until every node it points to has returned, so each node finishes after everything downstream of it. Reversing the finish order, or reading the finished stack from the top, therefore puts every node ahead of the nodes that depend on it.
By remembering which nodes are still open, meaning their call is on the call stack. An edge to a finished node is harmless, but an edge to an open node points back at something you are still inside, and following the call stack from that node to the top closes a loop.
Both run in O(V + E) time. Kahn's algorithm is iterative and gives the cycle check for free by counting emitted nodes; the DFS version is shorter if you already have a DFS written, but a recursive implementation can hit the recursion limit on very deep graphs.