Graph Algorithms BFS Dijkstras Distance between u and
Graph Algorithms BFS, Dijkstra’s
Distance between u and v Length of the shortest length path between u and v Distance between and ? 3
Breadth First Search (BFS) Is s connected to t? Build layers of vertices connected to s L 0 = {s} Lj : all nodes at distance j from s Assume L 0, . . , Lj have been constructed Lj+1 set of vertices not chosen yet but are connected to Lj Stop when new layer is empty
BFS Tree BFS naturally defines a tree rooted at s Lj forms the jth “level” in the tree u in Lj+1 is child of v in Lj from which it was “discovered” 1 2 7 Add nontree edges L 0 1 2 3 L 1 3 8 4 5 6 7 8 L 2 L 3
DFS Data Structures queue<Node> 1 1 vector<bool> 1 2 2 2 3 4 5 3 4 7 8 6 5 6 7 8 L 0 1 7 2 3 L 1 3 8 4 5 6 7 8 L 2 L 3
DFS(u) Mark u as explored and add u to R For each edge (u, v) If v is not explored then DFS(v)
Depth First Search (DFS) http: //xkcd. com/761/
A DFS run 1 1 2 7 2 3 8 4 4 Every nontree edge is u is explored between a For every unexplored neighbor v of u its node and ancestor DFS(v) DFS(u) 5 5 6 DFS tree 6 3 8 7
A DFS run using an explicit stack 7 8 1 2 7 76 3 3 8 5 4 4 5 5 3 6 2 3 1
http: //xkcd. com/173/
Finding cycles in O(n+m) • Run BFS or DFS • If an edge is considered and the node is already explored – That’s a cycle! 1 2 7 3 8 4 5 6
Shortest Path Problem http: //xkcd. com/85/
Driving Directions
Shortest Path problem Input: Directed graph G=(V, E) s 100 5 Edge lengths, le for e in E w 15 u “start” vertex s in V s s 5 5 u Output: All shortest paths from s to all nodes in V w u 15
Naïve Algorithm Ω(n!) time
Dijkstra’s shortest path algorithm E. W. Dijkstra (1930 -2002)
Dijkstra’s shortest path algorithm 1 3 u 1 1 4 s 2 2 w 2 3 43 y 1 4 2 x 2 z 54 d’(w) = min e=(u, w) in E, u in R d(u)+le d(s) = 0 d(u) = 1 d(w) = 2 d(x) = 2 d(y) = 3 d(z) = 4 s Input: Directed G=(V, E), le ≥ 0, s in V R = {s}, d(s) =0 While there is a x not in R with (u, x) in E, u in R Pick w that minimizes d’(w) Add w to R d(w) = d’(w) u Shortest paths w x y z
Couple of remarks The Dijkstra’s algo does not explicitly compute the shortest paths Can maintain “shortest path tree” separately Dijkstra’s algorithm does not work with negative weights
Dijkstra’s shortest path algorithm (runtime) d’(v) = min e=(u, v) in E, u in S d(u)+le Input: Directed G=(V, E), le ≥ 0, s in V S = {s}, d(s) =0 While there is a v not in S with (u, v) in E, u in S At most n iterations Pick w that minimizes d’(w) Add w to S d(w) = d’(w) O(mn) time bound is trivial O(m log n) time implementation is possible How? O(m) time
- Slides: 19