Graph Algorithms
Total Page:16
File Type:pdf, Size:1020Kb
Graph Algorithms Graphs and Graph Repre- sentations Graph Graph Algorithms Traversals COMP4128 Programming Challenges Directed Graphs and Cycles Strongly Connected Components Example: School of Computer Science and Engineering 2SAT UNSW Australia Minimum Spanning Trees Table of Contents 2 Graph Algorithms 1 Graphs and Graph Representations Graphs and Graph Repre- sentations 2 Graph Graph Traversals Traversals Directed Graphs and 3 Directed Graphs and Cycles Cycles Strongly Connected 4 Strongly Connected Components Components Example: 2SAT 5 Example: 2SAT Minimum Spanning Trees 6 Minimum Spanning Trees Graphs 3 Graph Algorithms Graphs and Graph Repre- sentations A graph is a collection of vertices and edges connecting Graph pairs of vertices. Traversals Directed Generally, graphs can be thought of as abstract Graphs and Cycles representations of objects and connections between those Strongly objects, e.g. intersections and roads, people and Connected Components friendships, variables and equations. Example: Many unexpected problems can be solved with graph 2SAT techniques. Minimum Spanning Trees Graphs 4 Graph Algorithms Graphs and Graph Repre- sentations Graph Many different types of graphs Traversals Directed graphs Directed Graphs and Acyclic graphs, including trees Cycles Weighted graphs Strongly Connected Flow graphs Components Other labels for the vertices and edges Example: 2SAT Minimum Spanning Trees Graph Representations 5 Graph Algorithms Graphs and Graph Repre- sentations Graph You’ll usually want to either use an adjacency list or an Traversals adjacency matrix to store your graph. Directed Graphs and An adjacency matrix is just a table (usually implemented Cycles as an array) where the jth entry in the ith row represents Strongly Connected the edge from i to j, or lack thereof. Components Example: Adjacency lists are a little more complex, but can be faster. 2SAT Minimum Spanning Trees Adjacency List 6 Graph Algorithms Graphs and Graph Repre- sentations The simplest way to implement adjacency lists is to create Graph a vector for every vertex. Traversals Directed There exist other representations that are slightly faster Graphs and Cycles and more efficient, like implementing your own linked list, Strongly but the time complexity of these is the same. Connected Components The simplest implementation with the best time Example: complexity, even if it slower by a constant factor, is usually 2SAT the best choice. Minimum Spanning Trees Adjacency List 7 Graph Algorithms Implementation for undirected graph #include <iostream > Graphs and #include <vector > Graph Repre- sentations int N = 1e6 + 5; // number of vertices in graph Graph vector <int> edges[N]; // each vertex has a list of connected vertices Traversals void add(int u, int v){ Directed // add from u to v Graphs and edges[u].push_back(v); Cycles // add from v to u edges[v].push_back(u); Strongly } Connected Components ... Example: // iterate over edges from u (since C++11) 2SAT for (int v : edges[u]) cout << v << '\n'; Minimum // iterate over edges from u (before C++11) Spanning vector <int >::iterator it = edges[u].begin(); Trees for (; it != edges[u].end(); ++it){ int v = *it; cout << v << '\n'; } Table of Contents 8 Graph Algorithms 1 Graphs and Graph Representations Graphs and Graph Repre- sentations 2 Graph Graph Traversals Traversals Directed Graphs and 3 Directed Graphs and Cycles Cycles Strongly Connected 4 Strongly Connected Components Components Example: 2SAT 5 Example: 2SAT Minimum Spanning Trees 6 Minimum Spanning Trees Graph Traversals 9 Graph Algorithms Graphs and Graph Repre- sentations There are two main ways to traverse a graph, which differ Graph in the order in which they visit new vertices: Traversals Depth-first search (DFS) - visit the first vertex insome Directed vertex’s adjacency list, and then recursively DFS on that Graphs and Cycles vertex, then move on; Strongly Breadth-first search (BFS) - visit the entire adjacency list Connected Components of some vertex, then recursively visit every unvisited vertex Example: in the adjacency list of those vertices. 2SAT Both can be implemented in O(jVj + jEj) time. Minimum Spanning Trees Depth-First Search 10 Graph Algorithms Graphs and Graph Repre- sentations Graph Traversals Depth-first search is a simple idea that can be extended to Directed Graphs and solve a huge amount of problems. Cycles Basic idea: for every vertex, recurse on everything it’s Strongly Connected adjacent to that hasn’t already been visited. Components Example: 2SAT Minimum Spanning Trees Depth-First Search 11 Graph Algorithms Graphs and Graph Repre- sentations Graph Implementation Traversals // global arrays are initialised to zero for you Directed bool seen[N]; Graphs and Cycles void dfs(int u){ if (seen[u]) return; Strongly seen[u] = true; Connected for (int v : edges[u]) dfs(v); Components } Example: 2SAT Minimum Spanning Trees Depth-First Search 12 Graph Algorithms In its simple form, it can already be used to solve several Graphs and problems - undirected cycle detection, connectivity, flood Graph Repre- sentations fill, etc. Graph It’s very useful, however, to introduce some more Traversals terminology to describe the parts of the DFS: Directed Graphs and Preorder(u) - the procedure to execute when u is reached, Cycles but before recursing on any of its neighbours; Strongly Inorder(u) - the procedure to execute after each neighbour Connected Components of u has finished its recursion; Example: Postorder(u) - the procedure to execute after u has 2SAT finished completely. Minimum Spanning Where in the implementation would each one of these go? Trees How would we modify the implementation to return a result found from the graph? Table of Contents 13 Graph Algorithms 1 Graphs and Graph Representations Graphs and Graph Repre- sentations 2 Graph Graph Traversals Traversals Directed Graphs and 3 Directed Graphs and Cycles Cycles Strongly Connected 4 Strongly Connected Components Components Example: 2SAT 5 Example: 2SAT Minimum Spanning Trees 6 Minimum Spanning Trees Directed Graph Cycle Detection 14 Graph Algorithms A simple cycle is a path through a graph consisting of Graphs and ≥ Graph Repre- n 1 distinct vertices and n distinct edges connecting sentations them (no vertex or edge is visited twice), where the start Graph Traversals and end of the path are the same vertex. Directed Given a graph, report whether or not this graph contains a Graphs and Cycles cycle. Assume that the graph is connected — if not, we Strongly can solve separately on each connected component. Connected Components If the graph is undirected, we can simply run a DFS on the Example: 2SAT graph, and return true if any vertex marked seen is visited Minimum again. (note: every undirected acyclic graph is a tree) Spanning Trees However, this doesn’t work for directed graphs, such as the diamond graph (1 ! 2 ! 3 4 1). Directed Graph Cycle Detection 15 Graph Algorithms Graphs and Graph Repre- This doesn’t work for directed graphs, such as the sentations diamond graph (1 ! 2 ! 3 4 1). Why not? Graph Traversals What does the DFS actually do? Directed Graphs and When visiting each vertex in our DFS, we check to see if Cycles any of the vertices we’re recursing on has been visited Strongly Connected before. Components Example: This doesn’t work because even if we’re visiting some 2SAT vertex that has been visited before, there’s no guarantee Minimum Spanning that that vertex can visit us. Trees Directed Graph Cycle Detection 16 Graph Algorithms Graphs and Graph Repre- However, we can see that the only time that some sentations already-visited vertex that we encounter can reach us is Graph Traversals when we’re currently within that vertex’s recursion stack. Directed Graphs and Now, if we had some easy way to check if we’re currently Cycles inside the recursion stack of a specific vertex, we’d have a Strongly Connected complete algorithm. Components It turns out this is easy to do — just mark each vertex Example: 2SAT “active” in a table during its preorder step, and unmark it Minimum Spanning during its postorder step. Trees Directed Graph Cycle Detection 17 Graph Algorithms Graphs and Graph Repre- sentations Implementation Graph // the vertices that are still marked active when this returns are the Traversals ones in the cycle we detected bool has_cycle(int u){ Directed if (seen[u]) return false; Graphs and seen[u] = true; Cycles active[u] = true; Strongly for (int v : edges[u]) { Connected if (active[v] || has_cycle(v)) return true; Components } active[u] = false; Example: return false; 2SAT } Minimum Spanning Trees Topological Sort 18 Graph Algorithms Graphs and Graph Repre- sentations Graph A topological sort of a graph is an ordering of the vertices Traversals that has the property that if some vertex u has a directed Directed Graphs and edge pointing to another vertex v, then v comes after u in Cycles the ordering. Strongly Connected Clearly, if the graph has a cycle, then there does not exist Components Example: a valid topological ordering of the graph. 2SAT Minimum Spanning Trees Topological Sort 19 Graph Algorithms Assuming the graph is acyclic (we refer to directed acyclic Graphs and Graph Repre- graphs as DAGs), how do we compute a topological sentations Graph ordering via DFS? Traversals We can directly use the reverse of the postorder sequence Directed Graphs and of the graph. Cycles Strongly The postorder sequence of the graph is an ordering of the Connected Components vertices of the graph in the order that each vertex reaches Example: