Directed Graphs

Total Page:16

File Type:pdf, Size:1020Kb

Directed Graphs Directed Graphs Directed Graphs Digraph. Set of objects with oriented pairwise connections. Ex. One-way street, hyperlink. Reference: Chapter 19, Algorithms in Java, 3rd Edition, Robert Sedgewick Robert Sedgewick and Kevin Wayne • Copyright © 2006 • http://www.Princeton.EDU/~cos226 2 Digraph Applications Ecological Food Web Food web graph. Digraph Vertex Edge ! Vertex = species. financial stock, currency transaction ! Edge = from prey to predator. transportation street intersection, airport highway, airway route scheduling task precedence constraint WordNet synset hypernym Web web page hyperlink game board position legal move telephone person placed call food web species predator-prey relation infectious disease person infection citation journal article citation object graph object pointer inheritance hierarchy class inherits from control flow code block jump http://www.twingroves.district96.k12.il.us/Wetlands/Salamander/SalGraphics/salfoodweb.giff 3 4 Some Digraph Problems Digraph Representation Transitive closure. Is there a directed path from v to w? Vertex names. ! This lecture: use integers between 0 and V-1. Strong connectivity. Are all vertices mutually reachable? ! Real world: convert between names and integers with symbol table. Topological sort. Can you draw the graph so that all edges point Orientation of edge matters. from left to right? 0 PERT/CPM. Given a set of tasks with precedence constraints, 7 8 what is the earliest that we can complete each task? 1 2 6 9 10 Shortest path. Given a weighted graph, find best route from s to t? 3 4 11 12 PageRank. What is the importance of a web page? 5 5 6 Adjacency Matrix Representation Adjacency List Representation Adjacency matrix representation. Adjacency list representation. Vertex indexed array of lists. ! Two-dimensional V ! V boolean array. ! Edge v"w in graph: adj[v][w] = true. to 0 0 1 2 3 4 5 6 7 8 9 10 11 12 0 0: 5 2 1 6 0 0 1 1 0 0 1 1 0 0 0 0 0 0 1: 1 0 0 0 0 0 0 0 0 0 0 0 0 0 2: 2 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 6 1 2 6 3: 3 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 1 0 0 0 0 0 0 0 0 0 4: 3 from 5 0 0 0 1 1 0 0 0 0 0 0 0 0 5: 4 3 3 4 3 4 6 0 0 0 0 1 0 0 0 0 0 0 0 0 6: 4 7 0 0 0 0 0 0 0 0 1 0 0 0 0 7: 8 8 0 0 0 0 0 0 0 0 0 0 0 0 0 5 5 9 0 0 0 0 0 0 0 0 0 0 1 1 1 8: 9 10 9 10 10 0 0 0 0 0 0 0 0 0 0 0 0 0 9: 10 11 12 11 0 0 0 0 0 0 0 0 0 0 0 0 1 10: 12 0 0 0 0 0 0 0 0 0 0 0 0 0 7 8 7 8 11 12 11 12 11: 12 12: 7 8 Adjacency List: Java Implementation Digraph Representations Implementation. Same as Graph, but only insert one copy of each edge. Digraphs are abstract mathematical objects. ! ADT implementation requires specific representation. ! Efficiency depends on matching algorithms to representations. public class Digraph { private int V; private Sequence<Integer>[] adj; Edge from Iterate over Representation Space v to w? edges leaving v? public Digraph(int V) { this.V = V; List of edges E + V E E adj = (Sequence<Integer>[]) new Sequence[V]; for (int v = 0; v < V; v++) Adjacency matrix V 2 1 V adj[v] = new Sequence<Integer>(); } Adjacency list E + V outdegree(v) outdegree(v) public void insert(int v, int w) { adj[v].add(w); } Digraphs in practice. # use adjacency list representation public Iterable<Integer> adj(int v) { return adj[v]; ! Bottleneck is iterating over edges leaving v. } ! Real world digraphs are sparse. } E is proportional to V 9 10 Reachability Digraph Search Goal. Find all vertices reachable from s along a directed path. s 11 12 Depth First Search Depth First Search Depth first search. Same as for undirected graphs. Remark. Same as undirected version, except Digraph instead of Graph. DFS (to visit a vertex v) public class DFSearcher { private boolean[] marked; Mark v as visited. Visit all unmarked vertices w adjacent to v. public DFSearcher(Digraph G, int s) { marked = new boolean[G.V()]; dfs(G, s); } private void dfs(Digraph G, int v) { marked[v] = true; Running time. O(E) since each edge examined at most once. for (int w : G.adj(v)) if (!marked[w]) dfs(G, w); } public boolean isReachable(int v) { return marked[v]; } } 13 14 Control Flow Graph Mark-Sweep Garbage Collector Control-flow graph. Roots. Objects known to be accessible by program (e.g., stack). ! Vertex = basic block (straight-line program). ! Edge = jump. Live objects. Objects that the program could get to by starting at a root and following a chain of pointers. easy to identify pointers in type-safe language Dead code elimination. Find (and remove) code blocks that are unreachable during execution. Mark-sweep algorithm. [McCarthy, 1960] dead code can arise from compiler optimization (or careless programmer) ! Mark: run DFS from roots to mark live objects. ! Sweep: if object is unmarked, it is garbage, so add to free list. Infinite loop detection. Exit block is unreachable from entry block. Caveat. Not all infinite loops are detectable. Extra memory. Uses 1 extra mark bit per object, plus DFS stack. 15 16 Depth First Search Breadth First Search DFS enables direct solution of simple digraph problems. Shortest path. Find the shortest directed path from s to t. ! Reachability. ! Cycle detection. BFS. Analogous to BFS in undirected graphs. ! Topological sort. ! Transitive closure. ! Find path from s to t. Basis for solving difficult digraph problems. ! Directed Euler path. ! Strong connected components. t s 17 18 Application: Web Crawler Web Crawler: Java Implementation Web graph. Vertex = website, edge = hyperlink. Queue<String> q = new Queue<String>(); queue of sites to crawl SET<String> visited = new SET<String>(); set of visited sites Goal. Crawl Internet, starting from some root website. String s = "http://www.princeton.edu"; Solution. BFS with implicit graph. q.enqueue(s); visited.add(s); start crawling from s while (!q.isEmpty()) { BFS. String v = q.dequeue(); System.out.println(v); ! Start at some root website, say http://www.princeton.edu. read in raw html In in = new In(v); http://xxx.yyy.zzz ! Queue Maintain a of websites to explore. String input = in.readAll(); ! Maintain a SET of discovered websites. String regexp = "http://(\\w+\\.)*(\\w+)"; Pattern pattern = Pattern.compile(regexp); ! Dequeue the next website, and enqueue websites to which it links Matcher matcher = pattern.matcher(input); (provided you haven't done so before). while (matcher.find()) { search using regular expression String w = matcher.group(); if (!visited.contains(w)) { visited.add(w); if unvisited, mark as visited Q. Why not use DFS? q.enqueue(w); and put on queue } } } 19 20 Transitive Closure Transitive Closure Transitive closure. Is there a directed path from v to w? G Transitive closure tc[v][w] = 1 iff path from v to w 21 22 Transitive Closure Transitive Closure: Java Implementation Transitive closure. Is there a directed path from v to w? Implementation. Use an array of DFSearcher objects. Lazy. Run separate DFS for each query. Eager. Run DFS from every vertex v; store results. public class TransitiveClosure { private DFSearcher[] tc; Method Preprocess Query Space public TransitiveClosure(Digraph G) { DFS (lazy) 1 E + V E + V tc = new Reachability[G.V()]; DFS (eager) E V 1 V2 for (int v = 0; v < G.V(); v++) tc[v] = new Reachability(G, v); } Remark. Directed problem is harder than undirected one. public boolean reachable(int v, int w) { return tc[v].isReachable(w); 2 Open research problem. O(1) query, O(V ) preprocessing time. } } is w reachable from v? 23 24 Topological Sort Topological Sort DAG. Directed acyclic graph. Topological sort. Redraw DAG so all edges point left to right. Observation. Not possible if graph has a directed cycle. 25 26 Application: Scheduling Topological Sort: DFS Scheduling. Given a set of tasks to be completed with precedence Topologically sort a DAG. constraints, in what order should we schedule the tasks? ! Run DFS. ! Reverse postorder numbering yields a topological sort. Graph model. ! Create a vertex v for each task. ! Create an edge v"w if task v must precede task w. Pf of correctness. When DFS backtracks from a vertex v, A ! Schedule tasks in topological order. all vertices reachable from v have already been explored. D Running time. O(E + V). 0. read programming assignment 1. download files E 2. write code no back edges in DAG … 12. sleep F H Q. If not a DAG, how would you identify a cycle? DFS tree 27 28 Topological Sort: Java Implementation Topological Sort: Applications public class TopologicalSorter { Topological sort applications. private int count; ! Causalities. private boolean[] visited; ! Compilation units. private int[] ts; ! Class inheritance. public TopologicalSorter(Digraph G) { ! Course prerequisites. visited = new boolean[G.V()]; ! Deadlocking detection. ts = new int[G.V()]; ! count = G.V(); Temporal dependencies. for (int v = 0; v < G.V(); v++) ! Pipeline of computing jobs. if (!visited[v]) tsort(G, v); ! Check for symbolic link loop. } ! Evaluate formula in spreadsheet. private void tsort(Digraph G, int v) { visited[v] = true; for (int w : G.adj(v)) if (!visited[w]) tsort(G, w); } ts[--count] = v; } assign numbers in reverse DFS postorder } 29 30 Program Evaluation and Review Technique / Critical Path Method Program Evaluation and Review Technique / Critical Path Method PERT/CPM.
Recommended publications
  • Practical Parallel Hypergraph Algorithms
    Practical Parallel Hypergraph Algorithms Julian Shun [email protected] MIT CSAIL Abstract v While there has been signicant work on parallel graph pro- 0 cessing, there has been very surprisingly little work on high- e0 performance hypergraph processing. This paper presents v0 v1 v1 a collection of ecient parallel algorithms for hypergraph processing, including algorithms for betweenness central- e1 ity, maximal independent set, k-core decomposition, hyper- v2 trees, hyperpaths, connected components, PageRank, and v2 v3 e single-source shortest paths. For these problems, we either 2 provide new parallel algorithms or more ecient implemen- v3 tations than prior work. Furthermore, our algorithms are theoretically-ecient in terms of work and depth. To imple- (a) Hypergraph (b) Bipartite representation ment our algorithms, we extend the Ligra graph processing Figure 1. An example hypergraph representing the groups framework to support hypergraphs, and our implementa- , , , , , , and , , and its bipartite repre- { 0 1 2} { 1 2 3} { 0 3} tions benet from graph optimizations including switching sentation. between sparse and dense traversals based on the frontier size, edge-aware parallelization, using buckets to prioritize processing of vertices, and compression. Our experiments represented as hyperedges, can contain an arbitrary number on a 72-core machine and show that our algorithms obtain of vertices. Hyperedges correspond to group relationships excellent parallel speedups, and are signicantly faster than among vertices (e.g., a community in a social network). An algorithms in existing hypergraph processing frameworks. example of a hypergraph is shown in Figure 1a. CCS Concepts • Computing methodologies → Paral- Hypergraphs have been shown to enable richer analy- lel algorithms; Shared memory algorithms.
    [Show full text]
  • Applications of DFS
    (b) acyclic (tree) iff a DFS yeilds no Back edges 2.A directed graph is acyclic iff a DFS yields no back edges, i.e., DAG (directed acyclic graph) , no back edges 3. Topological sort of a DAG { next 4. Connected components of a undirected graph (see Homework 6) 5. Strongly connected components of a drected graph (see Sec.22.5 of [CLRS,3rd ed.]) Applications of DFS 1. For a undirected graph, (a) a DFS produces only Tree and Back edges 1 / 7 2.A directed graph is acyclic iff a DFS yields no back edges, i.e., DAG (directed acyclic graph) , no back edges 3. Topological sort of a DAG { next 4. Connected components of a undirected graph (see Homework 6) 5. Strongly connected components of a drected graph (see Sec.22.5 of [CLRS,3rd ed.]) Applications of DFS 1. For a undirected graph, (a) a DFS produces only Tree and Back edges (b) acyclic (tree) iff a DFS yeilds no Back edges 1 / 7 3. Topological sort of a DAG { next 4. Connected components of a undirected graph (see Homework 6) 5. Strongly connected components of a drected graph (see Sec.22.5 of [CLRS,3rd ed.]) Applications of DFS 1. For a undirected graph, (a) a DFS produces only Tree and Back edges (b) acyclic (tree) iff a DFS yeilds no Back edges 2.A directed graph is acyclic iff a DFS yields no back edges, i.e., DAG (directed acyclic graph) , no back edges 1 / 7 4. Connected components of a undirected graph (see Homework 6) 5.
    [Show full text]
  • Practical Parallel Hypergraph Algorithms
    Practical Parallel Hypergraph Algorithms Julian Shun [email protected] MIT CSAIL Abstract v0 While there has been significant work on parallel graph pro- e0 cessing, there has been very surprisingly little work on high- v0 v1 v1 performance hypergraph processing. This paper presents a e collection of efficient parallel algorithms for hypergraph pro- 1 v2 cessing, including algorithms for computing hypertrees, hy- v v 2 3 e perpaths, betweenness centrality, maximal independent sets, 2 v k-core decomposition, connected components, PageRank, 3 and single-source shortest paths. For these problems, we ei- (a) Hypergraph (b) Bipartite representation ther provide new parallel algorithms or more efficient imple- mentations than prior work. Furthermore, our algorithms are Figure 1. An example hypergraph representing the groups theoretically-efficient in terms of work and depth. To imple- fv0;v1;v2g, fv1;v2;v3g, and fv0;v3g, and its bipartite repre- ment our algorithms, we extend the Ligra graph processing sentation. framework to support hypergraphs, and our implementations benefit from graph optimizations including switching between improved compared to using a graph representation. Unfor- sparse and dense traversals based on the frontier size, edge- tunately, there is been little research on parallel hypergraph aware parallelization, using buckets to prioritize processing processing. of vertices, and compression. Our experiments on a 72-core The main contribution of this paper is a suite of efficient machine and show that our algorithms obtain excellent paral- parallel hypergraph algorithms, including algorithms for hy- lel speedups, and are significantly faster than algorithms in pertrees, hyperpaths, betweenness centrality, maximal inde- existing hypergraph processing frameworks.
    [Show full text]
  • Adjacency Matrix
    CSE 373 Graphs 3: Implementation reading: Weiss Ch. 9 slides created by Marty Stepp http://www.cs.washington.edu/373/ © University of Washington, all rights reserved. 1 Implementing a graph • If we wanted to program an actual data structure to represent a graph, what information would we need to store? for each vertex? for each edge? 1 2 3 • What kinds of questions would we want to be able to answer quickly: 4 5 6 about a vertex? about edges / neighbors? 7 about paths? about what edges exist in the graph? • We'll explore three common graph implementation strategies: edge list , adjacency list , adjacency matrix 2 Edge list • edge list : An unordered list of all edges in the graph. an array, array list, or linked list • advantages : 1 2 3 easy to loop/iterate over all edges 4 5 6 • disadvantages : hard to quickly tell if an edge 7 exists from vertex A to B hard to quickly find the degree of a vertex (how many edges touch it) 0 1 2 3 4 56 7 8 (1, 2) (1, 4) (1, 7) (2, 3) 2, 5) (3, 6)(4, 7) (5, 6) (6, 7) 3 Graph operations • Using an edge list, how would you find: all neighbors of a given vertex? the degree of a given vertex? whether there is an edge from A to B? 1 2 3 whether there are any loops (self-edges)? • What is the Big-Oh of each operation? 4 5 6 7 0 1 2 3 4 56 7 8 (1, 2) (1, 4) (1, 7) (2, 3) 2, 5) (3, 6)(4, 7) (5, 6) (6, 7) 4 Adjacency matrix • adjacency matrix : An N × N matrix where: the non-diagonal entry a[i,j] is the number of edges joining vertex i and vertex j (or the weight of the edge joining vertex i and vertex j).
    [Show full text]
  • Introduction to Graphs
    Multidimensional Arrays & Graphs CMSC 420: Lecture 3 Mini-Review • Abstract Data Types: • Implementations: • List • Linked Lists • Stack • Circularly linked lists • Queue • Doubly linked lists • Deque • XOR Doubly linked lists • Dictionary • Ring buffers • Set • Double stacks • Bit vectors Techniques: Sentinels, Zig-zag scan, link inversion, bit twiddling, self- organizing lists, constant-time initialization Constant-Time Initialization • Design problem: - Suppose you have a long array, most values are 0. - Want constant time access and update - Have as much space as you need. • Create a big array: - a = new int[LARGE_N]; - Too slow: for(i=0; i < LARGE_N; i++) a[i] = 0 • Want to somehow implicitly initialize all values to 0 in constant time... Constant-Time Initialization means unchanged 1 2 6 12 13 Data[] = • Access(i): if (0≤ When[i] < count and Where[When[i]] == i) return Where[] = 6 13 12 Count = 3 Count holds # of elements changed Where holds indices of the changed elements. When[] = 1 3 2 When maps from index i to the time step when item i was first changed. Access(i): if 0 ≤ When[i] < Count and Where[When[i]] == i: return Data[i] else: return DEFAULT Multidimensional Arrays • Often it’s more natural to index data items by keys that have several dimensions. E.g.: • (longitude, latitude) • (row, column) of a matrix • (x,y,z) point in 3d space • Aside: why is a plane “2-dimensional”? Row-major vs. Column-major order • 2-dimensional arrays can be mapped to linear memory in two ways: 1 2 3 4 5 1 2 3 4 5 1 1 2 3 4 5 1 1 5 9 13 17 2 6 7 8 9 10 2 2 6 10 14 18 3 11 12 13 14 15 3 3 7 11 15 19 4 16 17 18 19 20 4 4 8 12 16 20 Row-major order Column-major order Addr(i,j) = Base + 5(i-1) + (j-1) Addr(i,j) = Base + (i-1) + 4(j-1) Row-major vs.
    [Show full text]
  • 9 the Graph Data Model
    CHAPTER 9 ✦ ✦ ✦ ✦ The Graph Data Model A graph is, in a sense, nothing more than a binary relation. However, it has a powerful visualization as a set of points (called nodes) connected by lines (called edges) or by arrows (called arcs). In this regard, the graph is a generalization of the tree data model that we studied in Chapter 5. Like trees, graphs come in several forms: directed/undirected, and labeled/unlabeled. Also like trees, graphs are useful in a wide spectrum of problems such as com- puting distances, finding circularities in relationships, and determining connectiv- ities. We have already seen graphs used to represent the structure of programs in Chapter 2. Graphs were used in Chapter 7 to represent binary relations and to illustrate certain properties of relations, like commutativity. We shall see graphs used to represent automata in Chapter 10 and to represent electronic circuits in Chapter 13. Several other important applications of graphs are discussed in this chapter. ✦ ✦ ✦ ✦ 9.1 What This Chapter Is About The main topics of this chapter are ✦ The definitions concerning directed and undirected graphs (Sections 9.2 and 9.10). ✦ The two principal data structures for representing graphs: adjacency lists and adjacency matrices (Section 9.3). ✦ An algorithm and data structure for finding the connected components of an undirected graph (Section 9.4). ✦ A technique for finding minimal spanning trees (Section 9.5). ✦ A useful technique for exploring graphs, called “depth-first search” (Section 9.6). 451 452 THE GRAPH DATA MODEL ✦ Applications of depth-first search to test whether a directed graph has a cycle, to find a topological order for acyclic graphs, and to determine whether there is a path from one node to another (Section 9.7).
    [Show full text]
  • A Low Complexity Topological Sorting Algorithm for Directed Acyclic Graph
    International Journal of Machine Learning and Computing, Vol. 4, No. 2, April 2014 A Low Complexity Topological Sorting Algorithm for Directed Acyclic Graph Renkun Liu then return error (graph has at Abstract—In a Directed Acyclic Graph (DAG), vertex A and least one cycle) vertex B are connected by a directed edge AB which shows that else return L (a topologically A comes before B in the ordering. In this way, we can find a sorted order) sorting algorithm totally different from Kahn or DFS algorithms, the directed edge already tells us the order of the Because we need to check every vertex and every edge for nodes, so that it can simply be sorted by re-ordering the nodes the “start nodes”, then sorting will check everything over according to the edges from a Direction Matrix. No vertex is again, so the complexity is O(E+V). specifically chosen, which makes the complexity to be O*E. An alternative algorithm for topological sorting is based on Then we can get an algorithm that has much lower complexity than Kahn and DFS. At last, the implement of the algorithm by Depth-First Search (DFS) [2]. For this algorithm, edges point matlab script will be shown in the appendix part. in the opposite direction as the previous algorithm. The algorithm loops through each node of the graph, in an Index Terms—DAG, algorithm, complexity, matlab. arbitrary order, initiating a depth-first search that terminates when it hits any node that has already been visited since the beginning of the topological sort: I.
    [Show full text]
  • CS302 Final Exam, December 5, 2016 - James S
    CS302 Final Exam, December 5, 2016 - James S. Plank Question 1 For each of the following algorithms/activities, tell me its running time with big-O notation. Use the answer sheet, and simply circle the correct running time. If n is unspecified, assume the following: If a vector or string is involved, assume that n is the number of elements. If a graph is involved, assume that n is the number of nodes. If the number of edges is not specified, then assume that the graph has O(n2) edges. A: Sorting a vector of uniformly distributed random numbers with bucket sort. B: In a graph with exactly one cycle, determining if a given node is on the cycle, or not on the cycle. C: Determining the connected components of an undirected graph. D: Sorting a vector of uniformly distributed random numbers with insertion sort. E: Finding a minimum spanning tree of a graph using Prim's algorithm. F: Sorting a vector of uniformly distributed random numbers with quicksort (average case). G: Calculating Fib(n) using dynamic programming. H: Performing a topological sort on a directed acyclic graph. I: Finding a minimum spanning tree of a graph using Kruskal's algorithm. J: Finding the minimum cut of a graph, after you have found the network flow. K: Finding the first augmenting path in the Edmonds Karp implementation of network flow. L: Processing the residual graph in the Ford Fulkerson algorithm, once you have found an augmenting path. Question 2 Please answer the following statements as true or false. A: Kruskal's algorithm requires a starting node.
    [Show full text]
  • Merkle Trees and Directed Acyclic Graphs (DAG) As We've Discussed, the Decentralized Web Depends on Linked Data Structures
    Merkle trees and Directed Acyclic Graphs (DAG) As we've discussed, the decentralized web depends on linked data structures. Let's explore what those look like. Merkle trees A Merkle tree (or simple "hash tree") is a data structure in which every node is hashed. +--------+ | | +---------+ root +---------+ | | | | | +----+---+ | | | | +----v-----+ +-----v----+ +-----v----+ | | | | | | | node A | | node B | | node C | | | | | | | +----------+ +-----+----+ +-----+----+ | | +-----v----+ +-----v----+ | | | | | node D | | node E +-------+ | | | | | +----------+ +-----+----+ | | | +-----v----+ +----v-----+ | | | | | node F | | node G | | | | | +----------+ +----------+ In a Merkle tree, nodes point to other nodes by their content addresses (hashes). (Remember, when we run data through a cryptographic hash, we get back a "hash" or "content address" that we can think of as a link, so a Merkle tree is a collection of linked nodes.) As previously discussed, all content addresses are unique to the data they represent. In the graph above, node E contains a reference to the hash for node F and node G. This means that the content address (hash) of node E is unique to a node containing those addresses. Getting lost? Let's imagine this as a set of directories, or file folders. If we run directory E through our hashing algorithm while it contains subdirectories F and G, the content-derived hash we get back will include references to those two directories. If we remove directory G, it's like Grace removing that whisker from her kitten photo. Directory E doesn't have the same contents anymore, so it gets a new hash. As the tree above is built, the final content address (hash) of the root node is unique to a tree that contains every node all the way down this tree.
    [Show full text]
  • Graph Algorithms G
    Bipartiteness Graph G = (V,E) is bipartite iff it can be partitioned into two sets of nodes A and B such that each edge has one end in A and the other Introduction to Algorithms end in B Alternatively: Graph Algorithms • Graph G = (V,E) is bipartite iff all its cycles have even length • Graph G = (V,E) is bipartite iff nodes can be coloured using two colours CSE 680 Question: given a graph G, how to test if the graph is bipartite? Prof. Roger Crawfis Note: graphs without cycles (trees) are bipartite bipartite: non bipartite Testing bipartiteness Toppgological Sort Method: use BFS search tree Recall: BFS is a rooted spanning tree. Algorithm: Want to “sort” or linearize a directed acyygp()clic graph (DAG). • Run BFS search and colour all nodes in odd layers red, others blue • Go through all edges in adjacency list and check if each of them has two different colours at its ends - if so then G is bipartite, otherwise it is not A B D We use the following alternative definitions in the analysis: • Graph G = (V,E) is bipartite iff all its cycles have even length, or • Graph G = (V, E) is bipartite iff it has no odd cycle C E A B C D E bipartit e non bipartite Toppgological Sort Example z PerformedonaPerformed on a DAG. A B D z Linear ordering of the vertices of G such that if 1/ (u, v) ∈ E, then u appears before v. Topological-Sort (G) 1. call DFS(G) to compute finishing times f [v] for all v ∈ V 2.
    [Show full text]
  • List Representation: Adjacency List – N Rows of the Adjacency Matrix Are
    List Representation: Adjacency List { n rows of the adjacency matrix are repre- sented as n linked lists { Declare an Array of size n e.g. A[1:::n] of Lists { A[i] is a pointer to the edges in E(G) starting at vertex i. Undirected graph: data in each list cell is a number indicating the adjacent vertex Weighted graph: data in each list cell is a pair (vertex, weight) 1 a b c e a [b,2] [c,6] [e,4] b a b [a,2] c a e d c [a,6] [e,3] [d,1] d c d [c,1] e a c e [a,4] [c,3] Properties: { the degree of any node is the number of elements in the list { O(e) to check for adjacency for e edges. { O(n + e) space for graph with n vertices and e edges. 2 Search and Traversal Techniques Trees and Graphs are models on which algo- rithmic solutions for many problems are con- structed. Traversal: All nodes of a tree/graph are exam- ined/evaluated, e.g. | Evaluate an expression | Locate all the neighbours of a vertex V in a graph Search: only a subset of vertices(nodes) are examined, e.g. | Find the first token of a certain value in an Abstract Syntax Tree. 3 Types of Traversals Binary Tree traversals: | Inorder, Postorder, Preorder General Tree traversals: | With many children at each node Graph Traversals: | With Trees as a special case of a graph 4 Binary Tree Traversal Recall a Binary tree | is a tree structure in which there can be at most two children for each parent | A single node is the root | The nodes without children are leaves | A parent can have a left child (subtree) and a right child (subtree) A node may be a record of information | A node is visited when it is considered in the traversal | Visiting a node may involve computation with one or more of the data fields at the node.
    [Show full text]
  • 6.042J Chapter 6: Directed Graphs
    “mcs-ftl” — 2010/9/8 — 0:40 — page 189 — #195 6 Directed Graphs 6.1 Definitions So far, we have been working with graphs with undirected edges. A directed edge is an edge where the endpoints are distinguished—one is the head and one is the tail. In particular, a directed edge is specified as an ordered pair of vertices u, v and is denoted by .u; v/ or u v. In this case, u is the tail of the edge and v is the ! head. For example, see Figure 6.1. A graph with directed edges is called a directed graph or digraph. Definition 6.1.1. A directed graph G .V; E/ consists of a nonempty set of D nodes V and a set of directed edges E. Each edge e of E is specified by an ordered pair of vertices u; v V . A directed graph is simple if it has no loops (that is, edges 2 of the form u u) and no multiple edges. ! Since we will focus on the case of simple directed graphs in this chapter, we will generally omit the word simple when referring to them. Note that such a graph can contain an edge u v as well as the edge v u since these are different edges ! ! (for example, they have a different tail). Directed graphs arise in applications where the relationship represented by an edge is 1-way or asymmetric. Examples include: a 1-way street, one person likes another but the feeling is not necessarily reciprocated, a communication channel such as a cable modem that has more capacity for downloading than uploading, one entity is larger than another, and one job needs to be completed before another job can begin.
    [Show full text]