1.87k likes | 2.04k Views
Graphs. Joe Meehean. Graphs. Vertices (nodes) connected by edges (pointers) Multiple incoming edges are OK Cycles are OK. Graphs. Generalization of trees both have nodes and edges Trees root has no incoming edges other nodes have exactly one Graphs n o restriction on incoming edges
E N D
Graphs Joe Meehean
Graphs Vertices (nodes) connected by edges (pointers) Multiple incoming edges are OK Cycles are OK
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
Graph Types • Directed • AKA (digraph) • Undirected We will manly consider directed graphs in class
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
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
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
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
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
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
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)
Implementation template <class K> class Vertex<K>{ //fields private: K data_; list<Vertex<K>*> successors_; friend Graph<K>; }
Implementation template <class K> class Graph<K>{ //fields private: // could use a list too set<Vertex<K>*> vertices_; intnumEdges_; //constructor public Graph(){ numEdges = 0; } }
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
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; }
Example Graph vertices: Vertex Vertex Cville data: data: Charlotte succs: succs: Vertex Dulles data: succs:
Uses for Graphs Representing real world problems Vertices represent things Edges represent relationships between things
Graph Examples 141 • Interdependent tasks • Vertices = tasks • Edge = “Must do before” • CS courses w/ prereqs 142 271 360 241 380 242
Graph Examples • State Transition Diagrams Flashing Yellow Yellow Red Flashing Red Green
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
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?
High Level Graph Operations • 2 orderly ways to traverse graph • depth-first search (DFS) • breadth-first search (BFS)
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
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
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)
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
DISCUSSION BREAK!!! B A Draw a potential call trace and visit order from C D C F E
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
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
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
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
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); }}}}
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)
DISCUSSION BREAK!!! C B A D E G F Write 2 dfs and 2 bfs orders starting at A
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
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
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
Review • Graphs are a generalization of trees • 2 ways to traverse • depth-first search (DFS) • breadth-first search (BFS)
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
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
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
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
Unweighted Shortest Path F E ShortestHops(A) C D Queue A B
Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F B
Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F D B
Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F D B
Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F D E B
Unweighted Shortest Path F E ShortestHops(A) C D Queue A B C F D E B