 Download Download Presentation Graphs

# Graphs

Télécharger la présentation ## Graphs

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Graphs Joe Meehean

2. Graphs Vertices (nodes) connected by edges (pointers) Multiple incoming edges are OK Cycles are OK

3. Graphs • Generalization of trees • both have nodes and edges • Trees • root has no incoming edges • other nodes have exactly one • Graphs • no restriction on incoming edges • may not contain an obvious starting node

4. Graph Types • Directed • AKA (digraph) • Undirected We will manly consider directed graphs in class

5. Graphs Newark 1.5hrs Charlotte 2hrs 1.25hrs 1.5hrs 1.25hrs 1hr Charlottesville Dulles 1hr • Can have labels (data) • in vertices (names) • on edges (weights or cost) • Ex: Airline Routes

6. Terminology Dulles Newark Predecessor Successor • Adjacent • vertex A is adjacent to vertex B if there is an edge between A and B (A,B) • Predecessor / Successor • two ends of a directed edge

7. Terminology • Path • sequence of vertices connected by edges • E.g., Charlottesville=> Dulles=> Charlotte • acyclic path • no vertex is repeated • Charlottesville=> Dulles=> Charlotte • cyclic path • some vertex is repeated • Newark=>Dulles=>Charlotte=>Newark • DAG: Directed Acyclic Graph • directed graph with no cycles

8. Terminology • Connected • undirected graph is connected if there is a path from every vertex to every other vertex • Strongly connected • directed graph that is connected • Complete graph • edge between every pair of vertices

9. Representing Graphs • One Graph class for the “whole thing” • Stores vertices • some graphs have a special root vertex (simple ptr) • others must keep all vertices • array, list, set, or map • Stores counts • # of vertices • # of edges

10. Representing Adjacency • Adjacency matrix • vertices are represented by integer • 2d array A • if edge between v & u, A[v][u] = true • weighted graphs, A[v][u] = weight • expensive in space: vertices2 • appropriate for dense graphs • nearly every vertex has an edge to nearly every other vertex • most graphs are not dense

11. Representing Adjacency • Adjacency lists • Option 1: Map • store a map of vertices to adjacent lists • Option 2: List in vertex class • Vertex class • stores data/label • adjacent vertices (successors in list or set) • predecessors (optional)

12. Implementation template <class K> class Vertex<K>{ //fields private: K data_; list<Vertex<K>*> successors_; friend Graph<K>; }

13. Implementation template <class K> class Graph<K>{ //fields private: // could use a list too set<Vertex<K>*> vertices_; intnumEdges_; //constructor public Graph(){ numEdges = 0; } }

14. Implemenation: Operations • addVertice • given vertex or data • addEdge • given between vertices m & n • getVertices • return list of all vertices • getSuccessors • given node n • hasEdge • given vertices m and n

15. Implementation // Optionally template <class K, class L> class Edge{ private: Vertex<K>* successor_; L label_; public: // constructor Edge(Vertex<K>* vertex, L label){ successor_ = vertex; label_ = label; } friend class Vertex; }

16. Example Graph vertices: Vertex Vertex Cville data: data: Charlotte succs: succs: Vertex Dulles data: succs:

17. Uses for Graphs Representing real world problems Vertices represent things Edges represent relationships between things

18. Graph Examples 141 • Interdependent tasks • Vertices = tasks • Edge = “Must do before” • CS courses w/ prereqs 142 271 360 241 380 242

19. Graph Examples • State Transition Diagrams Flashing Yellow Yellow Red Flashing Red Green

20. Graph Examples Start k = 0 • Control Flow Graphs • Program flow chart boolthisOrThat(){ intk = 0; while(cond1){ if(cond2){ //this }else{ //that } } return stuff; } cond1 cond2 this that return stuff

21. Power of Graphs • Graphs can answer questions like • Can I fly non-stop from Chicago to Tampa? • If not, what is the min hops? • How many CS classes must I take before CS360? • Can a variable be returned uninitialized?

22. Questions?

23. High Level Graph Operations • 2 orderly ways to traverse graph • depth-first search (DFS) • breadth-first search (BFS)

24. Depth-First Search • Can answer questions • is graph connected? • does graph have a cycle? • is there a path from vertex j to vertex k? • what vertices are reachable from vertex k? • Topological numbering • acyclical graphs • ordering where node’s # comes before all successors

25. Depth-First Search Idea Start at a given vertex v Follow an edge out of v (to u) Follow an edge out of u Getting as far away from v as possible When dead-end, go back one vertex and try other successors

26. Depth-First Search Algorithm • Start with all vertices marked unvisited • Select a vertex v • dfs(v) • mark v visited • foreach of v’s successors u • if u is unvisited: dfs(u)

27. DFS Example dfs(A) B A dfs(C) D C dfs(D) dfs(E) F E dfs(B) dfs(F) Visit order: A C D B F E Alternate order: A C F E D B

28. DISCUSSION BREAK!!! B A Draw a potential call trace and visit order from C D C F E

29. DISCUSSION BREAK!!! B A dfs(C) dfs(D) dfs(E) D C dfs(B) dfs(F) F E dfs(A) Visit order: C D B A F E

30. DFS Implementation void Graph::dfs(Vertex* v){ v->visited = true; list<Vertex*>::iterator iter; for(iter = v->successors.begin(); iter != v->successors.end(); iter++ ){ if( !(*iter)->visited ){ dfs(*iter); } } } • Visited/unvisited marker • boolean in each vertex

31. DFS Complexity • 1 recursive call with each vertex reachable from v • Each call goes through successor list • Time proportional to • # vertices reachable from v • # of outgoing edges from those vertices • Worst case • all vertices reachable from all vertices • O(V + E) • V is vertices in graph • E is edges in graph

32. Breadth-First Search • Idea • visit all nodes 1 step from v • visit all nodes 2 steps from v • … • Similar to level-order traversal of trees • Mark vertices to avoid visiting twice • Use BFS to… • find vertices reachable from some start vertex • find shortest # of hops from a vertex to another

33. BFS Implementation void bfs(Vertex* v){ queue<Vertex*> vertexQ; v->visted = true; vertexQ.push(v); while( !vertexQ.empty() ){ Vertex* curr = vertexQ.front(); vertexQ.pop(); list<Vertex*>::iterator iter; for(iter = curr->succ.begin(); iter != curr->succ.end(); iter++){ if( !(*iter)->visited ){ (*iter)->visited = true; vertexQ.push(*iter); }}}}

34. BFS Complexity • Every vertex enqueued/dequeued once • When a vertex is dequeued all successors are considered • Time proportional to… • # of vertices reachable from 1st vertex • # of outgoing edges from those vertices • assuming Q and iterator operators are O(1) • Worst-case time: O(V + E)

35. DISCUSSION BREAK!!! C B A D E G F Write 2 dfs and 2 bfs orders starting at A

36. DISCUSSION BREAK!!! C B A D E G F DFS: A B F G D E A B F E D G A D F G E B A D F E G B BFS: A B D F G E A D B F G E A D B F E G A B D F E G Write 2 dfs and 2 bfs orders starting at A

37. Uses for DFS • Path detection • is there a path from vertex j to vertex k? • can I fly from Lynchburg to Barcelona? • is 242 a prereq for 370? • Start with all vertices “unvisited” • dfs(j) • There is a path from j to k if k is marked visited

38. Modifying DFS for Actual Use • There is a path from j to k, if there is a path from any of j’s reachable vertices to k • boolisPath(Vertex* start, Vertex* end) • Base case • start == end, return true • Recursive case • if there is a path from any of start’s univisted successors to end, then return true • else return false

39. Questions?

40. Review • Graphs are a generalization of trees • 2 ways to traverse • depth-first search (DFS) • breadth-first search (BFS)

41. Finding Shortest Path F E 6 2 14 C 11 D 10 9 A 15 B 7 • Find shortest path between 2 vertices • Shortest # of hops • # of edges traversed • Shortest in cost • for weighted graphs

42. Unweighted Shortest Path • Goal • shortest # of hops from 1 vertex to all vertices • Input • graph and starting node • Output • graph with each node marked with distance • unreachable marked infinity • easy to calculate actual path

43. Unweighted Shortest Path • Use BFS • find all vertices within distance 1, 2, 3, …. • Additional book keeping in Vertex • boolean visited • found shortest path yet • initially false • int/float distance • # of hops in shortest path • initially ∞ • Vertex* path • vertex before this one on shortest path • initially NULL

44. Unweighted Shortest Path • Set distance of starting vertex to 0 • Set current vertex to starting vertex • Mark it visited • For each of current’s ∞ distance successors • set their distance to 1 + current’s distance • set their path to current vertex • add successor to queue • Take vertex off of queue, set to current • Go to 3, until queue is empty

45. Unweighted Shortest Path F E ShortestHops(A) C D Queue A B

46. Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F B

47. Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F D B

48. Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F D B

49. Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F D E B

50. Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F D E B