4.1 ■ Undirected Graphs Q&A Q. Why not jam all of the algorithms into Graph.java? A. Yes, we might just add query methods (and whatever private fields and methods each might need) to the basic Graph ADT definition. While this approach has some of the virtues of data abstraction that we have embraced, it also has some serious drawbacks, because the world of graph processing is significantly more expansive than the kinds of basic data structures treated in Section 1.3. Chief among these drawbacks are the following: ■ There are many more graph-processing operations to implement than we can accurately define in a single API. ■ Simple graph-processing tasks have to use the same API needed by complicated tasks. ■ One method can access a field intended for use by another method, contrary to encapsulation principles that we would like to follow. This situation is not unusual: APIs of this kind have come to be known as wide interfaces (see page 97). In a chapter filled with graph-processing algorithms, an API of this sort would be wide indeed. Q. Does SymbolGraph really need two passes? A. No. You could pay an extra lg N factor and support adj() directly as an ST instead of a Bag. We have an implementation along these lines in our book An Introduction to Programming in Java: An Interdisciplinary Approach. 557 558 CHAPTER 4 ■ Graphs EXERCISES 4.1.1 What is the maximum number of edges in a graph with V vertices and no parallel edges? What is the minimum number of edges in a graph with V vertices, none of which are isolated? tinyGex2.txt V 12 E 16 8 4 2 3 1 11 0 6 3 6 10 3 7 11 7 8 11 8 2 0 6 2 5 2 5 10 3 10 8 1 4 1 4.1.2 Draw, in the style of the figure in the text (page 524), the adjacency lists built by Graph’s input stream constructor for the file tinyGex2.txt depicted at left. 4.1.3 Create a copy constructor for Graph that takes as input a graph G and creates and initializes a new copy of the graph. Any changes a client makes to G should not affect the newly created graph. 4.1.4 Add a method hasEdge() to Graph which takes two int arguments v and w and returns true if the graph has an edge v-w, false otherwise. 4.1.5 Modify Graph to disallow parallel edges and self-loops. 4.1.6 Consider the four-vertex graph with edges 0-1, 1-2, 2-3, and 3-0. Draw an array of adjacency-lists that could not have been built calling addEdge() for these edges no matter what order. 4.1.7 Develop a test client for Graph that reads a graph from the input stream named as command-line argument and then prints it, relying on toString(). 4.1.8 Develop an implementation for the Search API on page 528 that uses UF, as described in the text. 4.1.9 Show, in the style of the figure on page 533, a detailed trace of the call dfs(0) for the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). Also, draw the tree represented by edgeTo[]. 4.1.10 Prove that every connected graph has a vertex whose removal (including all adjacent edges) will not disconnect the graph, and write a DFS method that finds such a vertex. Hint : Consider a vertex whose adjacent vertices are all marked. 4.1.11 Draw the tree represented by edgeTo[] after the call bfs(G, 0) in Algorithm 4.2 for the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). 4.1 4.1.12 What does the BFS tree tell us about the distance from v to w when neither is at the root? 4.1.13 Add distTo() method to the BreadthFirstPaths API and implementation, 4.1.14 Suppose you use a stack instead of a queue when running breadth-first search. Does it still compute shortest paths? Undirected Graphs 559 same lists as for list-of-edges input but order within lists is different a which returns the number of edges on the shortest path from the source to a given vertex. A distTo() query should run in constant time. ■ tinyGadj.txt V 13 E 13 0 1 2 5 6 3 4 5 4 5 6 7 8 9 10 11 12 11 12 4.1.15 Modify the input stream constructor for Graph to also allow adjacency lists from standard input (in a manner similar to SymbolGraph), as in the example tinyGadj.txt shown at right. After the number of vertices and edges, each line contains a vertex and its list of adjacent vertices. % java Graph tinyGadj.txt 13 vertices, 13 edges 0: 6 5 2 1 list order 1: 0 is reversed 2: 0 from input 3: 5 4 4: 6 5 3 5: 4 3 0 6: 4 0 7: 8 8: 7 9: 12 11 10 second 10: 9 representation 11: 12 9 of each edge appears in red 12: 11 9 4.1.16 The eccentricity of a vertex v is the the length of the shortest path from that vertex to the furthest vertex from v. The diameter of a graph is the maximum eccentricity of any vertex. The radius of a graph is the smallest eccentricity of any vertex. A center is a vertex whose eccentricity is the radius. Implement the following API: public class GraphProperties GraphProperties(Graph G) constructor (exception if G not connected) int eccentricity(int v) eccentricity of v int diameter() diameter of G int radius() radius of G int center() a center of G 4.1.18 The girth of a graph is the length of its shortest cycle. If a graph is acyclic, then its girth is infinite. Add a method girth() to GraphProperties that returns the girth of the graph. Hint : Run BFS from each vertex. The shortest cycle containing s is a shortest path from s to some vertex v, plus the edge from v back to s. 560 CHAPTER 4 ■ Graphs EXERCISES (continued) 4.1.19 Show, in the style of the figure on page 545, a detailed trace of CC for finding the connected components in the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). 4.1.20 Show, in the style of the figures in this section, a detailed trace of Cycle for finding a cycle in the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). What is the order of growth of the running time of the Cycle constructor, in the worst case? 4.1.21 Show, in the style of the figures in this section, a detailed trace of TwoColor for finding a two-coloring of the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). What is the order of growth of the running time of the TwoColor constructor, in the worst case? 4.1.22 Run SymbolGraph with movies.txt to find the Kevin Bacon number of this year’s Oscar nominees. 4.1.23 Write a program BaconHistogram that prints a histogram of Kevin Bacon numbers, indicating how many performers from movies.txt have a Bacon number of 0, 1, 2, 3, ... . Include a category for those who have an infinite number (not connected to Kevin Bacon). 4.1.24 Compute the number of connected components in movies.txt, the size of the largest component, and the number of components of size less than 10. Find the eccentricity, diameter, radius, a center, and the girth of the largest component in the graph. Does it contain Kevin Bacon? 4.1.25 Modify DegreesOfSeparation to take an int value y as a command-line argument and ignore movies that are more than y years old. 4.1.26 Write a SymbolGraph client like DegreesOfSeparation that uses depth-first search instead of breadth-first search to find paths connecting two performers, producing output like that shown on the facing page. 4.1 ■ Undirected Graphs 4.1.27 Determine the amount of memory used by Graph to represent a graph with V vertices and E edges, using the memory-cost model of Section 1.4. 4.1.28 Two graphs are isomorphic if there is a way to rename the vertices of one to make it identical to the other. Draw all the nonisomorphic graphs with two, three, four, and five vertices. 4.1.29 Modify Cycle so that it works even if the graph contains self-loops and parallel edges. % java DegreesOfSeparationDFS movies.txt Source: Bacon, Kevin Query: Kidman, Nicole Bacon, Kevin Mystic River (2003) O’Hara, Jenny Matchstick Men (2003) Grant, Beth ... [123 movies ] (!) Law, Jude Sky Captain... (2004) Jolie, Angelina Playing by Heart (1998) Anderson, Gillian (I) Cock and Bull Story, A (2005) Henderson, Shirley (I) 24 Hour Party People (2002) Eccleston, Christopher Gone in Sixty Seconds (2000) Balahoutis, Alexandra Days of Thunder (1990) Kidman, Nicole 561 562 CHAPTER 4 ■ Graphs CREATIVE PROBLEMS 4.1.30 Eulerian and Hamiltonian cycles. Consider the graphs defined by the following four sets of edges: 0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8 0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8 0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8 4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-8 1-5 9-8 4-5 4-7 Which of these graphs have Euler cycles (cycles that visit each edge exactly once)? Which of them have Hamilton cycles (cycles that visit each vertex exactly once)? 4.1.31 Graph enumeration. How many different undirected graphs are there with V vertices and E edges (and no parallel edges)? 4.1.32 Parallel edge detection. Devise a linear-time algorithm to count the parallel edges in a graph. 4.1.33 Odd cycles. Prove that a graph is two-colorable (bipartite) if and only if it contains no odd-length cycle. 4.1.34 Symbol graph. Implement a one-pass SymbolGraph (it need not be a Graph client). Your implementation may pay an extra log V factor for graph operations, for symbol-table lookups. 4.1.35 Biconnectedness. A graph is biconnected if every pair of vertices is connected by two disjoint paths. An articulation point in a connected graph is a vertex that would disconnect the graph if it (and its adjacent edges) were removed. Prove that any graph with no articulation points is biconnected. Hint : Given a pair of vertices s and t and a path connecting them, use the fact that none of the vertices on the path are articulation points to construct two disjoint paths connecting s and t. 4.1.36 Edge connectivity. A bridge in a graph is an edge that, if removed, would separate a connected graph into two disjoint subgraphs. A graph that has no bridges is said to be edge connected. Develop a DFS-based data type for determing whether a given graph is edge connected. 4.1.37 Euclidean graphs. Design and implement an API EuclideanGraph for graphs whose vertices are points in the plane that include coordinates. Include a method show() that uses StdDraw to draw the graph. 4.1 ■ Undirected Graphs 4.1.38 Image processing. Implement the flood fill operation on the implicit graph defined by connecting adjacent points that have the same color in an image. 563 564 CHAPTER 4 ■ Graphs EXPERIMENTS 4.1.39 Random graphs. Write a program ErdosRenyiGraph that takes integer values V and E from the command line and builds a graph by generating E random pairs of integers between 0 and V1. Note: This generator produces self-loops and parallel edges. 4.1.40 Random simple graphs. Write a program RandomSimpleGraph that takes integer values V and E from the command line and produces, with equal likelihood, each of the possible simple graphs with V vertices and E edges. 4.1.41 Random sparse graphs. Write a program RandomSparseGraph to generate random sparse graphs for a well-chosen set of values of V and E such that you can use it to run meaningful empirical tests on graphs drawn from the Erdös-Renyi model. 4.1.42 Random Euclidean graphs. Write a EuclideanGraph client (see Exercise 4.1.37) RandomEuclideanGraph that produces random graphs by generating V random points in the plane, then connecting each point with all points that are within a circle of radius d centered at that point. Note : The graph will almost certainly be connected if d is larger than the threshold value lg V/ V and almost certainly disconnected if d is smaller than that value. 4.1.43 Random grid graphs. Write a EuclideanGraph client RandomGridGraph that generates random graphs by connecting vertices arranged in a V-by- V grid to their neighbors (see Exercise 1.5.15). Augment your program to add R extra random edges. For large R, shrink the grid so that the total number of edges remains about V. Add an option such that an extra edge goes from a vertex s to a vertex t with probability inversely proportional to the Euclidean distance between s and t. 4.1.44 Real-world graphs. Find a large weighted graph on the web—perhaps a map with distances, telephone connections with costs, or an airline rate schedule. Write a program RandomRealGraph that builds a graph by choosing V vertices at random and E edges at random from the subgraph induced by those vertices. 4.1.45 Random interval graphs. Consider a collection of V intervals on the real line (pairs of real numbers). Such a collection defines an interval graph with one vertex corresponding to each interval, with edges between vertices if the corresponding intervals intersect (have any points in common). Write a program that generates V random intervals in the unit interval, all of length d, then builds the corresponding interval graph. Hint: Use a BST. 4.1 ■ Undirected Graphs 4.1.46 Random transportation graphs. One way to define a transportation system is with a set of sequences of vertices, each sequence defining a path connecting the vertices. For example, the sequence 0-9-3-2 defines the edges 0-9, 9-3, and 3-2. Write a EuclideanGraph client RandomTransportation that builds a graph from an input file consisting of one sequence per line, using symbolic names. Develop input suitable to allow you to use your program to build a graph corresponding to the Paris Métro system. Testing all algorithms and studying all parameters against all graph models is unrealistic. For each problem listed below, write a client that addresses the problem for any given input graph, then choose among the generators above to run experiments for that graph model. Use your judgment in selecting experiments, perhaps in response to results of previous experiments. Write a narrative explaining your results and any conclusions that might be drawn. 4.1.47 Path lengths in DFS. Run experiments to determine empirically the probability that DepthFirstPaths finds a path between two randomly chosen vertices and to calculate the average length of the paths found, for various graph models. 4.1.48 Path lengths in BFS. Run experiments to determine empirically the probability that BreadthFirstPaths finds a path between two randomly chosen vertices and to calculate the average length of the paths found, for various graph models. 4.1.49 Connected components. Run experiments to determine empirically the distribution of the number of components in random graphs of various types, by generating large numbers of graphs and drawing a histogram. 4.1.50 Two-colorable. Most graphs are not two-colorable, and DFS tends to discover that fact quickly. Run empirical tests to study the number of edges examined by TwoColor, for various graph models. 565
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )