Presentation is loading. Please wait.

Presentation is loading. Please wait.

Graph Algorithms BFS, DFS, Dijkstra’s.

Similar presentations


Presentation on theme: "Graph Algorithms BFS, DFS, Dijkstra’s."— Presentation transcript:

1 Graph Algorithms BFS, DFS, Dijkstra’s

2 Distance between u and v
Length of the shortest length path between u and v Distance between and ? 3

3 Breadth First Search (BFS)
Is s connected to t? Build layers of vertices connected to s Lj : all nodes at distance j from s L0 = {s} Assume L0,..,Lj have been constructed Lj+1 set of vertices not chosen yet but are connected to Lj Stop when new layer is empty

4 BFS Tree BFS naturally defines a tree rooted at s Add non-tree edges
Lj forms the jth “level” in the tree u in Lj+1 is child of v in Lj from which it was “discovered” 1 7 1 L0 2 3 L1 2 3 8 4 5 4 5 7 8 L2 6 6 L3

5 DFS Data Structures queue<Node> 1 2 3 4 5 7 8 6
vector<bool> 1 2 3 4 5 6 7 8 1 L0 1 7 2 3 L1 2 3 8 4 5 4 5 7 8 L2 6 6 L3

6 DFS(u) Mark u as explored and add u to R For each edge (u,v)
If v is not explored then DFS(v)

7 Depth First Search (DFS)

8 Every non-tree edge is between a node and its ancestor
A DFS run Every non-tree edge is between a node and its ancestor DFS(u) u is explored For every unexplored neighbor v of u DFS(v) 1 1 7 2 2 3 8 4 4 5 5 DFS tree 6 6 3 8 7

9 A DFS run using an explicit stack
7 8 1 7 7 6 3 2 3 5 8 4 4 5 5 3 6 2 3 1

10

11 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 7 2 3 8 4 5 6

12 Shortest Path Problem

13 Driving Directions

14 Shortest Path problem s 100 Input: Directed graph G=(V,E) w
15 5 s u w 100 Input: Directed graph G=(V,E) Edge lengths, le for e in E “start” vertex s in V 15 5 s u w 5 s u Output: All shortest paths from s to all nodes in V

15 Naïve Algorithm Ω(n!) time

16 Dijkstra’s shortest path algorithm
E. W. Dijkstra ( )

17 Dijkstra’s shortest path algorithm
1 d’(w) = min e=(u,w) in E, u in R d(u)+le 1 2 4 3 y 4 3 u d(s) = 0 d(u) = 1 s x 2 4 d(w) = 2 d(x) = 2 d(y) = 3 d(z) = 4 w z 5 4 2 s w Input: Directed G=(V,E), le ≥ 0, s in V u R = {s}, d(s) =0 Shortest paths x While there is a x not in R with (u,x) in E, u in R z y Pick w that minimizes d’(w) Add w to R d(w) = d’(w)

18 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

19 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(m) time O(mn) time bound is trivial O(m log n) time implementation is possible How?


Download ppt "Graph Algorithms BFS, DFS, Dijkstra’s."

Similar presentations


Ads by Google