Sub topic 3
Topological Sorting from Finish Order
This chapter assumes you know recursive DFS, visited sets, and discovery and finish times from the earlier chapters. It also assumes you are comfortable with Big-O notation.
Topological Sorting from Finish Order
A topological order lists the vertices of a directed acyclic graph (DAG) so that every edge points forward in the list. A vertex finishes only after everything reachable from it has finished. So if you reverse the finish order, each vertex comes before all of its descendants.
def topological_sort(graph):
visited = set()
postorder = []
def visit(node):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
postorder.append(node) # appended when the node finishes
for node in graph:
if node not in visited:
visit(node)
return postorder[::-1]
deps = {
"shirt": ["tie"],
"tie": ["jacket"],
"pants": ["shoes", "jacket"],
"shoes": [],
"jacket": [],
}
print(topological_sort(deps)) # ['pants', 'shoes', 'shirt', 'tie', 'jacket']Finding Connected Components
In an undirected graph, each DFS that the outer loop starts from an unvisited vertex reaches exactly one connected component. To count components, count those launches. To label them, record a component id inside visit.
DFS on Grids: Flood Fill and Counting Islands
A grid is a graph without an explicit edge list. Each cell is a vertex, and its four orthogonal neighbors are its edges. Flood fill is DFS from one cell that stops at boundaries, at water, and at cells it has already seen. Counting islands means counting flood-fill launches. A common bug is checking bounds after indexing into the grid; check them first. On large grids, recursion depth can reach rows × cols, so use an explicit stack there.
Path Finding and Backtracking Search
Backtracking is DFS over a space of partial solutions. You add a choice, recurse, and then undo the choice. To list every simple path, remove a vertex from the current path's set when you return from it, so other paths can use it again. The number of paths can grow exponentially, so prune branches early.
Strongly Connected Components
A strongly connected component (SCC) is a maximal set of vertices where each vertex can reach every other. Both standard algorithms run in O(V + E):
- Kosaraju's algorithm runs DFS once to get finish order. It then runs DFS on the reversed graph in decreasing finish order, and each tree of that second pass is one SCC.
- Tarjan's algorithm uses a single DFS. It tracks low-link values and a stack of vertices.
Bridges and Articulation Points with Low-Link Values
low[v] is the smallest discovery time reachable from v's subtree using at most one back edge. A tree edge (u, v) is a bridge if low[v] > disc[u]. A non-root vertex u is an articulation point if some child v has low[v] >= disc[u]. The root is an articulation point if it has two or more children in the DFS tree.
Choosing Between DFS, BFS, and Iterative Deepening
| Need | Choose |
|---|---|
| Structure: cycles, topological order, SCCs, bridges | DFS |
| Fewest edges in an unweighted graph | BFS |
| Shortest solution with little memory in a huge or infinite space | Iterative deepening |
Exercise
Why does reversing the DFS finish order give a valid topological order, and what goes wrong on a graph with a cycle?
Show answer
For any edge u→v in a DAG, v finishes before u. Either v was already finished when DFS examined the edge, or DFS visits v and finishes it inside u's call. Reversing the finish order therefore puts u before v. With a cycle, some edge points back to an ancestor that is still open. That edge ends up pointing backward in the list, and in fact no valid order exists.
Exercise
In the grid ["101", "010", "101"], with 4-directional adjacency, how many islands are there?
Show answer
5. No two "1" cells share a side, so each one is its own island.