? We can check if two vertices are connected using DFS. 84
? We can check if a graph is acyclic/cyclic using DFS. 85
? There is a cycle iff we found an edge from current vertex to a visiting vertex (called backward edge) 86
proc DFS(u): mark u as “visiting” for each neighbor v of u if v is marked as “visiting” we found a cycle! else if v is marked as “unvisited” DFS(v) mark u as “visited” 87
Topological Sort Goal : Given a directed acyclic graph, order the vertices such that if there is a path from u to v , then u appears before v in the output. 88
Goal : Given a directed acyclic graph, order the vertices such that if there is a path from u to v , then u appears before v in the output. A BACFED? BCAFED? BFACED? B C E D F 89
Idea : The first vertex marked “visited” can appear last in the topological order. A B C E D F 90
Now, we remove that vertex from consideration, and repeat -- the next vertex marked as visited can appear last in the topological sort order. A B C E D F 91
proc DFS(u): for each unvisited neighbor v of u DFS(v) push u onto a stack To output in topological sort order, pop from stack and print after completing DFS. 92
Dijkstra’s Algorithm 93
Single-Source Shortest Path • Problem : Given a weighted graph G and a vertex v in G, find the shortest (or least cost) path from v to all other vertices. • Restrict ourselves to positive weight. 94
A 1 5 3 B C 3 5 1 1 F E D 4 2 Shortest Path from A to D = A-C-E-D (Cost = 8) 95
• Must keep track of smallest distance so far. • If we found a new, shorter path, update the distance. 96
u w 10 2 v 6 Let d[v] be the current known shortest distance from u to v. d[v] = 6, d[w] = 10 97
u w 8 2 v 6 We just found a shorter path from u to w. Update d[w] = d[v] + cost(v,w). We call this step relax(v,w). 98
proc relax (v,w): Let d = d[v] + cost(v,w) if d[w] > d d[w] = d 99
u 8 w 12 6 11 6 If d[w] is the smallest among the “remaining” vertices, then d[w] is the smallest possible (can’t be relaxed further) 100
Recommend
More recommend