graph
play

Graph Ooi Wei Tsang School of Computing, NUS 1 A graph consists - PowerPoint PPT Presentation

Graph Ooi Wei Tsang School of Computing, NUS 1 A graph consists of edges and vertices. 2 v u A vertex u is a neighbor of v, if there is an edge from v to u. We say u is adjacent to v. The number of neighbors of a vertex is called degree.


  1. ? We can check if two vertices are connected using DFS. 84

  2. ? We can check if a graph is acyclic/cyclic using DFS. 85

  3. ? There is a cycle iff we found an edge from current vertex to a visiting vertex (called backward edge) 86

  4. 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

  5. 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

  6. 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

  7. Idea : The first vertex marked “visited” can appear last in the topological order. A B C E D F 90

  8. 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

  9. 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

  10. Dijkstra’s Algorithm 93

  11. 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

  12. 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

  13. • Must keep track of smallest distance so far. • If we found a new, shorter path, update the distance. 96

  14. 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

  15. 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

  16. proc relax (v,w): Let d = d[v] + cost(v,w) if d[w] > d d[w] = d 99

  17. 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