Lecture 24: Graph Traversals and Implementations

10/21/2020

Note

Graph Traversals

Shortest Path Problem

BreadthFirstSearch for Google Maps

Graph API

Graph Representations

Graph API Decision #1: Integer Vertices

Graph API

public class Graph { public Graph(int V); // Create empty graph with v vertices public void addEdge(int v, int w); // add an edge v-w Iterable<Integer> adj(int v); // vertices adjacent to v int V(); // number of vertices int E(); // number of edges }
/** degree of vertex v in graph G */ public static int degree(Graph G, int v) { int degree = 0; for (int w : G.adj(v)) { degree += 1; } return degree; }
/** Prints out all the edges in a graph */ public static void print(Graph G) { for (int v = 0; v < G.V(); v += 1) { for (int w : G.adj(v)) { System.out.println(v + "-" + w); } } }

Graph API and DepthFirstPaths

Graph Representation and Graph Algorithm Runtimes

Graph Representations

Graph Printing Runtime

More Graph Representations

Graph Printing Runtime

Barebones Undirected Graph Implementation

public class Graph { private final int V; private List<Integer>[] adj; public Graph(int V) { this.V = V; adj = (List<Integer>[]) new ArrayList[V]; for (int v = 0; v < V; v++) { adj[v] = new ArrayList<Integer>(); } } public void addEdge(int v, int w) { adj[v].add(w); adj[w].add(v); } public Iterable<Integer> adj(int v) { return adj[v]; } }

Graph Traversal Implementations and Runtime

Depth Fist Search Implementation

public class Paths { public Paths(Graph G, int s); // Find all paths from G boolean hasPathTo(int v); // is there a path from s to v? Iterable<Integer> pathTo(int v); // path from s to v (if any) }

DepthFirstPaths Demo

DepthFirstPaths, Recursive Implementation

public class DepthFirstPaths { private boolean[] marked; private int[] edgeTo; private int s; public DepthFirstPaths(Graph G, int s) { ... dfs(G, s); } public void dfs(Graph G, int v) { marked[v] = true; for (int w : G.adj(v)) { if (!marked[w]) { edgeTo[w] = v; dfs(G, w); } } } public boolean hasPathTo(int v) { return marked[v]; } public Iterable<Integer> pathTo(int v) { if (!hasPathTo(v)) return null; List<Integer> path = new ArrayList<>(); for (int x = v; x !=s; x = edgeTo[x]) { path.add(x); } path.add(s); Collections.reverse(path); return path; } }

Runtime for DepthFirst Paths

Runtime for DepthFirstPaths

BreadthFirstPaths Implementation

public class BreadthFirstPaths { private boolean[] marked; private int[] edgeTo; ... private void bfs(Graph G, int s) { Queue<Integer> fringe = new Queue<Integer>(); fringe.enqueue(s); marked[s] = true; while (!fringe.isEmpty()) { int v = fringe.dequeue(); for (int w : G.adj(v)) { if (!marked[w]) { fringe.enqueue(w); marked[w] = true; edgeTo[w] = v; } } } } }

Layers of Abstraction

Clients and Our Graph API

Runtime for DepthFirstPaths

Summary

Summary

Discussion Review

Graphs

Graph Representations

Graph Searches

Dijkstra's Algorithm

A*