Graph Traversals

Graph Problems

  • 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

Graph Traversals

Topological Sorting

  • 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; // using stack analogous to reversing list b/c LIFO

    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); // after each DFS is done, "visit" vertex by pushing on stack
    }
}
  • Works even when starting from vertices not indegree 0
  • Finding Level-Order
  • DFS written recursively has implicit fringe → recursive call stack of vertices

results matching ""

    No results matching ""