Graph Traversals
- Runtime
- Each vertex visited exactly once, each visit = constant time
- Each edge considered once
- Space
- Recursive call stack depth
- Space of recursive algorithm = depth of call stack
- Indegree 0 vertices → , have to look at lists w/ total length
- Only works if graph is acyclic → if cyclic b/c can't have circular dependencies
- No indegree 0 vertices → cyclic →
- Topological ordering only possible iff graph is directed acyclic graph (no directed cycles)
- Linearizes graph
- Graph Problems
Implementation
public class DepthFirstOrder {
private boolean[] marked;
private Stack<Integer> reversePostorder;
public DepthFirstOrder(Digraph G) {
reversePostorder = new Stack<>();
marked = new boolean[G.V()];
for (int v = 0; v < G.V(); v++) {
if (!marked[v]) {
dfs(G, v);
}
}
}
private void dfs(Digraph G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) {
dfs(G, w);
}
}
reversePostorder.push(v);
}
}
- Works even when starting from vertices not indegree 0
- Finding Level-Order
- DFS written recursively has implicit fringe → recursive call stack of vertices