1 Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Size: px
Start display at page:

Download "1 Copyright 2012 by Pearson Education, Inc. All Rights Reserved."

Transcription

1 CHAPTER 22 Graphs and Applications Objectives To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem ( 22.1). To describe the graph terminologies: vertices, edges, simple graphs, weighted/unweighted graphs, and directed/undirected graphs ( 22.2). To represent vertices and edges using lists, adjacent matrices, and adjacent lists ( 22.3). To model graphs using the Graph class ( 22.4). To display graphs visually ( 22.5). To represent the traversal of a graph using the Tree class ( 22.6). To design and implement depth-first search ( 22.7). To solve the connected-circle problem using depth-first search ( 22.8). To design and implement breadth-first search ( 22.9). To solve the nine-tail problem using breadth-first search ( 22.10). 1

2 22.1 Introduction Key Point: Many real-world problems can be solved using graph algorithms. Graphs are useful in modeling and solving real-world problems. For example, the problem to find the minimal number of flights between two cities can be modeled using a graph, where the vertices represent cities and the edges represent the flights between two adjacent cities, as shown in Figure The problem of finding the minimal number of connecting flights between two cities is reduced to finding a shortest path between two vertices in a graph. Seatt le Chicago Bost on Denver New York San Francisco Kansas City Los Angeles At lanta Dallas Houston Miami Figure 22.1 A graph can be used to model the flights between the cities. The study of graph problems is known as graph theory. Graph theory was founded by Leonard Euler in 1736, when he introduced graph terminology to solve the famous Seven Bridges of Königsberg problem. The city of Königsberg, Prussia (now Kaliningrad, Russia) was divided by the Pregel River. There were two islands on the river. The city and islands were connected by seven bridges, as shown in Figure 22.2a. 2

3 The question is, can one take a walk, cross each bridge exactly once, and return to the starting point? Euler proved that it is not possible. A A C Island 1 D Island 2 C D B B (a) Seven bridges sketch (b) Graph model Figure 22.2 Seven bridges connected islands and land. To establish a proof, Euler first abstracted the Königsberg city map by eliminating all streets, producing the sketch shown in Figure 22.2a. Second, he replaced each land mass with a dot, called a vertex or a node, and each bridge with a line, called an edge, as shown in Figure 22.2b. This structure with vertices and edges is called a graph. Looking at the graph, we ask whether there is a path starting from any vertex, traversing all edges exactly once, and returning to the starting vertex. Euler proved that for such path to exist, each vertex must have an even number of edges. Therefore, the Seven Bridges of Königsberg problem has no solution. Graph problems are often solved using algorithms. Graph algorithms have many applications in various areas, such as in computer science, mathematics, biology, engineering, economics, genetics, and social sciences. This chapter presents the algorithms for depth-first search and breadth-first search, and their applications. The next chapter presents the algorithms for finding a minimum spanning tree and shortest paths in weighted graphs, and their applications Basic Graph Terminologies 3

4 Key Point: A graph consists of vertices and edges that connect the vertices. This chapter does not assume that the reader has prior knowledge of graph theory or discrete mathematics. We use plain and simple terms to define graphs. What is a graph? A graph is a mathematical structure that represents relationships among entities in the real world. For example, the graph in Figure 22.1 represents the flights among cities, and the graph in Figure 22.2b represents the bridges among land masses. A graph consists of a nonempty set of vertices (also called nodes or points), and a set of edges that connect the vertices. For convenience, we define a graph as G = (V, E), where V represents a set of vertices and E represents a set of edges. For example, V and E for the graph in Figure 22.1 are as follows: V = ["Seattle", "San Francisco", "Los Angeles", "Denver", "Kansas City", "Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"] E = [["Seattle", "San Francisco"], ["Seattle", "Chicago"], ["Seattle", "Denver"], ["San Francisco", "Denver"],... ] A graph may be directed or undirected. In a directed graph, each edge has a direction, which indicates that you can move from one vertex to the other through the edge. You may model parent/child relationships using a directed graph, where an edge from vertex A to B indicates that A is a parent of B. Figure 22.3a shows a directed graph. In an undirected graph, you can move in both directions between vertices. The graph in Figure 22.1 is undirected. 4

5 Peter Jane A D Cindy Mark B E Wendy C (a) A directed graph (b) A complete graph Figure 22.3 Graphs may appear in many forms. Edges may be weighted or unweighted. For example, you may assign a weight for each edge in the graph in Figure 22.1 to indicate the flight time between two cities. Two vertices in a graph are said to be adjacent if they are connected by the same edge. Similarly two edges are said to be adjacent if they are connected to the same vertex. An edge in a graph that joins two vertices is said to be incident to both vertices. The degree of a vertex is the number of edges incident to it. Two vertices are called neighbors if they are adjacent. Similarly two edges are called neighbors if they are adjacent. A loop is an edge that links a vertex to itself. If two vertices are connected by two or more edges, these edges are called parallel edges. A simple graph is one that has no loops and parallel edges. A complete graph is the one in which every two pairs of vertices are connected, as shown in Figure 22.3b. Assume that the graph is connected and undirected. A spanning tree of a graph is a subgraph that is a tree and connects all vertices in the graph. Pedagogical NOTE 5

6 Before we introduce graph algorithms and applications, it is helpful to get acquainted with graphs using an interactive tool from as shown in Figure The tool allows you to add/remove/move vertices and draw edges using mouse gestures. You can also find depth-first search trees and breadth-first search trees, and a shortest path between two vertices. Figure 22.4 You can use the tool to create a graph with mouse gestures and show DFS/BFS and shortest paths Representing Graphs Key Point: The vertices and edges can be stored in arrays or lists. To write a program that processes and manipulates graphs, you have to store or represent graphs in the computer Representing Vertices 6

7 The vertices can be stored in a list. For example, you can store all the city names in the graph in Figure 22.1 using the following list: vertices = ["Seattle", "San Francisco", "Los Angeles", "Denver", "Kansas City", "Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"] NOTE: The vertices can be objects of any type. For example, you may consider cities as objects that contain the information such as name, population, and mayor. So, you may define vertices as follows: city0 = City("Seattle", , "Greg Nickels")... city11 = City("Houston", , "Bill White") vertices = [city0, city1,..., city11] def class City: def init (self, cityname, population, mayor): self.cityname = cityname self.population = population self.mayor = mayor def getcityname(self): return self.cityname def getpopulation(self): return self.population def getmayor(self): return self.mayor def setmayor(mayor): self.mayor = mayor def setpopulation(population): self.population = population The vertices can be conveniently labeled using natural numbers 0, 1, 2,..., n - 1, for a graph for n vertices. So, vertices[0] represents "Seattle", vertices[1] represents "San Francisco", and so on, as shown in Figure

8 vertices[0] Seattle vertices[1] San Francisco vertices[2] Los Angeles vertices[3] Denver vertices[4] Kansas City vertices[5] Chicago vertices[6] Boston vertices[7] New York vertices[8] Atlanta vertices[9] Miami vertices[10] Dallas vertices[11] Houston Figure 22.5 A list stores the vertex names. NOTE: You can reference a vertex by its name or its index, whichever is convenient. Obviously, it is easy to access a vertex via its index in a program Representing Edges: Edge List The edges can be represented using a nested list. For example, you can store all the edges in the graph in Figure 22.1 using the following list: edges = [ [0, 1], [0, 3], [0, 5], [1, 0], [1, 2], [1, 3], [2, 1], [2, 3], [2, 4], [2, 10], [3, 0], [3, 1], [3, 2], [3, 4], [3, 5], [4, 2], [4, 3], [4, 5], [4, 7], [4, 8], [4, 10], [5, 0], [5, 3], [5, 4], [5, 6], [5, 7], [6, 5], [6, 7], [7, 4], [7, 5], [7, 6], [7, 8], [8, 4], [8, 7], [8, 9], [8, 10], [8, 11], [9, 8], [9, 11], [10, 2], [10, 4], [10, 8], [10, 11], [11, 8], [11, 9], [11, 10] ] 8

9 This representation is known as the edge lists. The edges in Figure 22.3a can be represented as follows: edges = [[0, 2], [1, 2], [2, 4], [3, 4]] Representing Edges: Edge Objects Another way to represent the edges is to define edges as objects and store the edges in a list. The Edge class can be defined as follows: class Edge: def init (self, u, v): self.u = u self.v = v For example, you can store all the edges in the graph in Figure 22.1 using the following list: edgelist = [] edgelist.append(edge(0, 1)) edgelist.append(edge(0, 3)) edgelist.append(edge(0, 5))... Storing Edge objects in a list is useful if you don t know the edges in advance. Representing edges using a nested list or Edge objects in and is intuitive for input, but not efficient for internal processing. The next two sections introduce the representation of graphs using adjacency matrices and adjacency lists. These two data structures are efficient for processing graphs Representing Edges: Adjacency Matrices Assume that the graph has n vertices. You can use a two-dimensional n n matrix, say adjacencymatrix, to represent edges. Each element in the array is 0 or 1. adjacencymatrix[i][j] is 1 if there is an edge from vertex i to vertex j; otherwise, adjacencymatrix[i][j] is 0. If the graph is undirected, the matrix is symmetric, because adjacencymatrix[i][j] is the same as adjacencymatrix[j][i]. For example, the edges in the graph in Figure 22.1 can be represented using an adjacency matrix as follows: 9

10 adjacencymatrix = [ [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0], # Seattle [1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], # San Francisco [0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], # Los Angeles [1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0], # Denver [0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0], # Kansas City [1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0], # Chicago [0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0], # Boston [0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0], # New York [0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1], # Atlanta [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1], # Miami [0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1], # Dallas [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0] # Houston ] The adjacency matrix for the directed graph in Figure 22.3a can be represented as follows: int[][] a = [[0, 0, 1, 0, 0], # Peter [0, 0, 1, 0, 0], # Jane [0, 0, 0, 0, 1], # Mark [0, 0, 0, 0, 1], # Cindy [0, 0, 0, 0, 0] # Wendy ] Representing Edges: Adjacency Lists To represent edges using adjacency lists, define a list of adjacency lists. The list has n entries. Each entry is an adjacency list. The adjacency list for vertex i contains all the vertices j such that there is an edge from vertex i to vertex j. For example, to represent the edges in the graph in Figure 22.1, you may create a list of adjacency lists as follows: neighbors = [[1, 3, 5], [0, 2, 3], [1, 3, 4, 10], [0, 1, 2, 4, 5], [2, 3, 4, 5, 7, 8, 10], [0, 3, 4, 6, 7], [5, 7], [4, 5, 6, 8], [4, 7, 9, 10, 11], [8, 11], [2, 4, 8, 11], [8, 9, 10]] neighbors[0] contains all vertices adjacent to vertex 0 (i.e., Seattle), neighbors[1] contains all vertices adjacent to vertex 1 (i.e., San Francisco), and so on, as shown in Figure

11 Seattle San Francisco Los Angeles Denver Kansas City Chicago Boston New York Atlanta Miami Dallas Houston neighbors[0] neighbors[1] neighbors[2] neighbors[3] neighbors[4] neighbors[5] neighbors[6] neighbors[7] neighbors[8] neighbors[9] neighbors[10] neighbors[11] [1, 3, 5] [0, 2, 3] [1, 3, 4, 10] [0, 1, 2, 4, 5] [2, 3, 4, 5, 7, 8, 10] [0, 3, 4, 6, 7] [5, 7] [4, 5, 6, 8] [4, 7, 9, 10, 11] [8, 11] [2, 4, 8, 11] [8, 9, 10] Figure 22.6 Edges in the graph in Figure 22.1 are represented using linked lists. To represent the edges in the graph in Figure 22.3a, you may create a list of lists as follows: neighbors = [[2], [2], [4], [4], [ ]] neighbors[0] contains all vertices pointed from vertex 0 via directed edges, lists[1] contains all vertices pointed from vertex 1 via directed edges, and so on, as shown in Figure Peter Jane Mark Cindy neighbors[0] neighbors[1] neighbors[2] neighbors[3] [2] [2] [4] [4] Wendy neighbors[4] [ ] Figure 22.7 Edges in the graph in Figure 22.3a are represented using linked lists. NOTE: 11

12 You can represent a graph using an adjacency matrix or adjacency lists. Which one is better? If the graph is dense (i.e., there are a lot of edges), using an adjacency matrix is preferred. If the graph is very sparse (i.e., very few edges), using adjacency lists is better, because using an adjacency matrix would waste a lot of space. Both adjacency matrices and adjacency lists may be used in a program to make algorithms more efficient. For example, it takes O(1) constant time to check whether two vertices are connected using an adjacency matrix and it takes linear time O(m) to print all edges in a graph using adjacency lists, where m is the number of edges. NOTE: Adjacency matrices and adjacency lists are two common representations for graphs, but they are not the only ways to represent graphs. For example, you may define a vertex as an object with a method getneighbors() that returns all its neighbors. For simplicity, the text will use adjacency lists to represent graphs. Other representations will be explored in the exercises. Check point 28.1 What is the famous Seven Bridges of Königsberg problem? 28.2 What is a graph? Explain the following terms: undirected graph, directed graph, weighted graph, degree of a vertex, parallel edge, simple graph, and complete graph How do you represent vertices in a graph? How do you represent edges using an edge array? How do you represent an edge using an edge object? How do you represent edges using an adjacency matrix? How do you represent edges using adjacency lists? 12

13 28.4 Represent the following graph using an edge array, a list of edge objects, an adjacent matrix, and an adjacent list, respectively Modeling Graphs Key Point: The Graph interface defines the common operations for a graph. What are the common operations for a graph? In general, you need to get the number of vertices in a graph, get all vertices in a graph, get the vertex object with a specified index, get the index of the vertex with a specified name, get the neighbors for a vertex, get the degree for a vertex, clear the graph, add a new vertex, add a new edge, perform a depth-first search, and perform a breadth-first search. Depth-first search and breadth-first search will be introduced in the next section. The Graph class can be designed as shown in Figure

14 Graph vertices: list neighbors: list of adjacency list Graph(vertexList: list, edgelist: list) getadjacencylist(edgelist: list): list getsize(): int getvertices(): list getvertex(index): object getindex(v: object): int getneighbors(index: int): list getdegree(v: object ): i nt printedges(): None clear(): None addvertex(v: object): None addedge(u: object, v: object): None +dfs(ind ex: in t): Tree +bfs(ind ex: in t): Tree Stores vertices. Stores edges. Constructs a graph with the specified vertices and edges. Returns an adjacency list from edgelist. Returns the number of vertices in the graph. Returns the vertices in the graph. Ret urns th e vertex at the s pecifi ed i ndex. Returns th e index for the specified vertex. Returns the neighbors of vertex with the specified index. Returns th e degree for a specified vertex. Prints the edges. Clears the graph. Adds a vertex to the graph. Adds an edge (from u to v) to the graph. Obtains a depth -first search tree. Obtains a bread th-first search tree. Figure 22.8 The Graph class defines the common operations for all types of graphs. Assume the class is available. Listing 22.1 gives a test program that creates a graph for the one in Figure 22.1 and another graph for the one in Figure 22.3a. Listing 22.1 TestGraph.py 1 from Graph import Graph 2 3 # Create vertices for graph in Figure vertices = ["Seattle", "San Francisco", "Los Angeles", 5 "Denver", "Kansas City", "Chicago", "Boston", "New York", 6 "Atlanta", "Miami", "Dallas", "Houston"] 7 8 # Create an edge list for graph in Figure edges = [ 10 [0, 1], [0, 3], [0, 5], 11 [1, 0], [1, 2], [1, 3], 12 [2, 1], [2, 3], [2, 4], [2, 10], 13 [3, 0], [3, 1], [3, 2], [3, 4], [3, 5], 14 [4, 2], [4, 3], [4, 5], [4, 7], [4, 8], [4, 10], 15 [5, 0], [5, 3], [5, 4], [5, 6], [5, 7], 16 [6, 5], [6, 7], 17 [7, 4], [7, 5], [7, 6], [7, 8], 18 [8, 4], [8, 7], [8, 9], [8, 10], [8, 11], 19 [9, 8], [9, 11], 20 [10, 2], [10, 4], [10, 8], [10, 11], 21 [11, 8], [11, 9], [11, 10] 22 ] graph1 = Graph(vertices, edges) 25 print("the vertices in graph1: " + str(graph1.getvertices())) 14

15 26 print("the number of vertices in graph1: " + str(graph1.getsize())) 27 print("the vertex with index 1 is " + graph1.getvertex(1)) 28 print("the index for Miami is " + str(graph1.getindex("miami"))) 29 print("the degree for Miami is " + str(graph1.getdegree("miami"))) 30 print("the edges for graph1:") 31 graph1.printedges() graph1.addvertex("savannah") 34 graph1.addedge("atlanta", "Savannah") 35 graph1.addedge("savannah", "Atlanta") 36 print("\nthe edges for graph1 after adding a new vertex and edges:") 37 graph1.printedges() # List of Edge objects for graph in Figure 16.3(a) 40 names = ["Peter", "Jane", "Mark", "Cindy", "Wendy"] 41 edges = [[0, 2], [1, 2], [2, 4], [3, 4]] # Create a graph with 5 vertices 44 graph2 = Graph(names, edges) 45 print("\nthe number of vertices in graph2: " 46 + str(graph2.getsize())) 47 print("the edges for graph2:") 48 graph2.printedges() Sample output The vertices in graph1: ['Seattle', 'San Francisco', 'Los Angeles', 'Denver', 'Kansas City', 'Chicago', 'Boston', 'New York', 'Atlanta', 'Miami', 'Dallas', 'Houston'] The number of vertices in graph1: 12 The vertex with index 1 is San Francisco The index for Miami is 9 The degree for Miami is 2 The edges for graph1: Seattle (0): (0, 1) (0, 3) (0, 5) San Francisco (1): (1, 0) (1, 2) (1, 3) Los Angeles (2): (2, 1) (2, 3) (2, 4) (2, 10) Denver (3): (3, 0) (3, 1) (3, 2) (3, 4) (3, 5) Kansas City (4): (4, 2) (4, 3) (4, 4) (4, 5) (4, 7) (4, 8) (4, 10) Chicago (5): (5, 0) (5, 3) (5, 4) (5, 5) (5, 7) (5, 11) Boston (6): (6, 5) (6, 7) New York (7): (7, 4) (7, 5) (7, 6) (7, 8) Atlanta (8): (8, 4) (8, 7) (8, 9) (8, 10) (8, 11) Miami (9): (9, 8) (9, 11) Dallas (10): (10, 2) (10, 4) (10, 8) (10, 11) Houston (11): (11, 10) (11, 8) (11, 9) The edges for graph1 after adding a new vertex and edges: Seattle (0): (0, 1) (0, 3) (0, 5) San Francisco (1): (1, 0) (1, 2) (1, 3) Los Angeles (2): (2, 1) (2, 3) (2, 4) (2, 10) Denver (3): (3, 0) (3, 1) (3, 2) (3, 4) (3, 5) Kansas City (4): (4, 2) (4, 3) (4, 4) (4, 5) (4, 7) (4, 8) (4, 10) Chicago (5): (5, 0) (5, 3) (5, 4) (5, 5) (5, 7) (5, 11) Boston (6): (6, 5) (6, 7) New York (7): (7, 4) (7, 5) (7, 6) (7, 8) Atlanta (8): (8, 4) (8, 7) (8, 9) (8, 10) (8, 11) (8, 12) Miami (9): (9, 8) (9, 11) Dallas (10): (10, 2) (10, 4) (10, 8) (10, 11) Houston (11): (11, 10) (11, 8) (11, 9) 15

16 Savannah (12): (12, 8) The number of vertices in graph2: 5 The edges for graph2: Peter (0): (0, 2) Jane (1): (1, 2) Mark (2): (2, 4) Cindy (3): (3, 4) Wendy (4): The program creates graph1 for the graph in Figure 22.1 in lines The vertices for graph1 are created in lines 3 6. The edges for graph1 are created in The edges are represented using a list of adjacency lists. For each row i in the list, neighbors[i] contains all the vertices adjacent to i. The program invokes the method in the Graph class to get vertices (line 25), get the number of vertices (line 26), get the vertex for the specified index (line 27), get the index for the specified vertex (line 28), get the degree of a vertex (line 29), and print all edges (line 31). The program adds a new vertex using the addvertex method (line 33) and adds a new edge using the addedge method (lines 34-35). Note that the addedge(u, v) method adds an edge from vertex u to v, where u and v are not indices, but are of the vertex type. The program creates graph2 for the graph in Figure 22.3a in lines and displays its edges (line 48). Note that both graph1 and graph2 contain the vertices of strings. The vertices are associated with indices 0, 1,..., n-1. The index is the location of the vertex in vertices. For example, the index of vertex Miami is 9. Now we turn our attention to implementing the class in Listings Listing 22.2 Graph.py 1 from Queue import Queue 2 3 class Graph: 4 def init (self, vertices, edges): 5 self.vertices = vertices 6 self.neighbors = self.getadjacnecylists(edges) 16

17 7 8 # Return a list of adjacency lists for edges 9 def getadjacnecylists(self, edges): 10 neighbors = [] 11 for i in range(len(self.vertices)): 12 neighbors.append([]) # Each element is another list for i in range(len(edges)): 15 u = edges[i][0] 16 v = edges[i][1] 17 neighbors[u].append(v) # Insert a neighbor for u return neighbors # Return the number of vertices in the graph 22 def getsize(self): 23 return len(self.vertices) # Return the vertices in the graph 26 def getvertices(self): 27 return self.vertices # Return the vertex at the specified index 30 def getvertex(self, index): 31 return self.vertices[index] # Return the index for the specified vertex 34 def getindex(self, v): 35 return self.vertices.index(v) # Return the neighbors of vertex with the specified index 38 def getneighbors(self, index): 39 return self.neighbors[index] # Return the degree for a specified vertex 42 def getdegree(self, v): 43 return len(self.neighbors[self.getindex(v)]) # Print the edges 46 def printedges(self): 47 for u in range(0, len(self.neighbors)): 48 print(self.getvertex(u) + " (" + str(u), end = "): ") 49 for j in range(len(self.neighbors[u])): 50 print("(" + str(u) + ", " + 51 str(self.neighbors[u][j]), end = ") ") 52 print() # Clear graph 55 def clear(self): 56 vertices = [] 57 neighbors = [] # Add a vertex to the graph 60 def addvertex(self, vertex): 61 if not (vertex in self.vertices): 62 self.vertices.append(vertex) 63 self.neighbors.append([]) # add a new empty adjacency list # Add an undirected edge to the graph 66 def addedge(self, u, v): 67 if u in self.vertices and v in self.vertices: 68 indexu = self.getindex(u) 69 indexv = self.getindex(v) 70 if not (indexv in self.neighbors[indexu]): 71 self.neighbors[indexu].append(indexv) 72 17

18 73 # Obtain a DFS tree starting from vertex v 74 # To be discussed in Section def dfs(self, v): 76 searchorders = [] 77 parent = len(self.vertices) * [-1] # Initialize parent[i] to # Mark visited vertices 80 isvisited = len(self.vertices) * [False] # Recursively search 83 self.dfshelper(v, parent, searchorders, isvisited) # Return a search tree 86 return Tree(v, parent, searchorders, self.vertices) # Recursive method for DFS search 89 def dfshelper(self, v, parent, searchorders, isvisited): 90 # Store the visited vertex 91 searchorders.append(v) 92 isvisited[v] = True # Vertex v visited for i in self.neighbors[v]: 95 if not isvisited[i]: 96 parent[i] = v # The parent of vertex i is v 97 # Recursive search 98 self.dfshelper(i, parent, searchorders, isvisited) # Starting bfs search from vertex v 101 # To be discussed in Section def bfs(self, v): 103 searchorders = [] 104 parent = len(self.vertices) * [-1] # Initialize parent[i] to queue = Queue() # the Queue class is defined in Chapter isvisited = len(self.vertices) * [False] 108 queue.enqueue(v) # Enqueue v 109 isvisited[v] = True # Mark it visited while not queue.isempty(): 112 u = queue.dequeue() # Dequeue to u 113 searchorders.append(u) # u searched 114 for w in self.neighbors[u]: 115 if not isvisited[w]: 116 queue.enqueue(w) # Enqueue w 117 parent[w] = u # The parent of w is u 118 isvisited[w] = True # Mark it visited return Tree(v, parent, searchorders, self.vertices) # Tree class will be discussed in Section class Tree: 124 def init (self, root, parent, searchorders, vertices): 125 self.root = root # The root of the tree 126 # Store the parent of each vertex in a list 127 self.parent = parent 128 # Store the search order in a list 129 self.searchorders = searchorders 130 self.vertices = vertices # vertices of the graph # Return the root of the tree 133 def getroot(self): 134 return self.root # Return the parent of vertex v 137 def getparent(self, index): 138 return self.parent[index] 18

19 # Return an array representing search order 141 def getsearchorders(self): 142 return self.searchorders # Return number of vertices found 145 def getnumberofverticesfound(self): 146 return len(self.searchorders) # Return the path of vertices from a vertex index to the root 149 def getpath(self, index): 150 path = [] while index!= -1: 153 path.append(self.vertices[index]) 154 index = self.parent[index] return path # Print a path from the root to vertex v 159 def printpath(self, index): 160 path = self.getpath(index) 161 print("a path from " + str(self.vertices[self.root]) + " to " str(self.vertices[index]), end = ": ") 163 for i in range(len(path) - 1, -1, -1): 164 print(path[i], end = " ") # Print the whole tree 167 def printtree(self): 168 print("root is: " + str(self.vertices[self.root])) 169 print("edges: ", end = "") 170 for i in range(len(self.parent)): 171 if self.parent[i]!= -1: 172 # Display an edge 173 print("(" + str(self.vertices[self.parent[i]]) ", " + str(self.vertices[i]), end = ") ") print() The Graph class uses the data field vertices (line 5) to store vertices in a list and neighbors (line 6) to store edges in a list of adjacency lists. Neighbors[i] stores all vertices adjacent to vertex i. The getadjacencylists(edges) method builds the adjacency lists from the edge list (lines 9-19). The getsize() method returns the number of vertices in the graph (lines 22-23). The getvertice() method returns the vertices in the graph (lines 26-27). The getvertex(index) method returns the vertex at the specified index (lines 30-31). The getindex(v) method returns the index for the vertex (lines 34-35). The getneighbors(index) method returns the neighbors for the vertex at the specified index (lines 38-39). The getdegree(v) method returns the degree of the vertex (lines 42-43). The printedges() method prints all edges of the graph (lines 46-52). The clear() method clears the graph (lines 55-57). The addvertex(v) method adds the vertex to the graph (lines 60-63) if the a vertex 19

20 is not in the graph. The addedge(u, v) method adds an edge from vertex u to v to the graph (lines 66-71). The method first checks whether the vertices are in the graph (line 67) and then checks if the edge is already in the graph (line 70). Note that this method adds an edge (u, v) to the graph, but it does not add an edge (v, u) to the graph. The code in lines gives the methods for finding a depth-first search tree and a breadth-first search tree, which will be introduced in Graph Visualization Key Point: To display a graph visually, each vertex must be assigned a location. The preceding section introduced how to model a graph using the Graph class. This section introduces how to display graphs graphically. In order to display a graph, you need to know where each vertex is displayed and the name of each vertex. To ensure a graph can be displayed, we define a class named Displayable with the methods for obtaining x-, y-coordinates, and name in Listing 22.3 and make vertices instances of Displayable. Listing 22.3 Displayable.py 1 class Displayable: 2 def getx(self): # Get x-coordinate of the vertex 3 return def gety(self): # Get y-coordinate of the vertex 6 return def getname(self): # Get display name of the vertex 9 return "" A graph with Displayable vertices can now be displayed on a canvas named GraphView as shown in Listing Listing 22.4 GraphView.py 1 from tkinter import * # Import tkinter 2 from Graph import Graph 3 4 class GraphView(Canvas): 5 def init (self, graph, container, width = 800, height = 450): 20

21 6 super(). init (container, width = width, height = height) 7 self.graph = graph 8 self.drawgraph() 9 10 def drawgraph(self): 11 vertices = self.graph.getvertices() 12 for i in range(self.graph.getsize()): 13 x = vertices[i].getx() 14 y = vertices[i].gety() 15 name = vertices[i].getname() # Display a vertex 18 self.create_oval(x - 2, y - 2, x + 2, y + 2, 19 fill = "black") 20 # Display the name 21 self.create_text(x, y - 8, text = str(name)) # Draw edges for pair of vertices 24 for i in range(self.graph.getsize()): 25 neighbors = self.graph.getneighbors(i) 26 x1 = self.graph.getvertex(i).getx() 27 y1 = self.graph.getvertex(i).gety() 28 for v in neighbors: 29 x2 = self.graph.getvertex(v).getx() 30 y2 = self.graph.getvertex(v).gety() 31 # Draw an edge for (i, v) 32 self.create_line(x1, y1, x2, y2) To display a graph on a canvas, simply create an instance of GraphView by passing the graph as an argument in the constructor (line 5). The class for the vertex of the graph must extend the Displayable class in order to display the vertices (lines 12 21). For each vertex index i, invoking self.graph.getneighbors(i) returns its adjacency list (line 11). From this list, you can find all vertices that are adjacent to i and draw a line to connect i with its adjacent vertex (lines 28 36). Listing 22.5 gives an example of displaying the graph in Figure 22.1, as shown in Figure Listing 22.5 DisplayUSMap.py 1 from Displayable import Displayable 2 3 class City(Displayable): 4 def init (self, name, x, y): 5 self.name = name 6 self.x = x 7 self.y = y 8 9 # Override the getx method 10 def getx(self): 11 return self.x # Override the gety method 14 def gety(self): 15 return self.y 21

22 16 17 # Override the getname method 18 def getname(self): 19 return self.name vertices = [City("Seattle", 75, 50), City("San Francisco", 50, 210), 22 City("Los Angeles", 75, 275), City("Denver", 275, 175), 23 City("Kansas City", 400, 245), 24 City("Chicago", 450, 100), City("Boston", 700, 80), 25 City("New York", 675, 120), City("Atlanta", 575, 295), 26 City("Miami", 600, 400), City("Dallas", 408, 325), 27 City("Houston", 450, 360)] # Edge array for graph in Figure edges = [ 31 [0, 1], [0, 3], [0, 5], 32 [1, 0], [1, 2], [1, 3], 33 [2, 1], [2, 3], [2, 4], [2, 10], 34 [3, 0], [3, 1], [3, 2], [3, 4], [3, 5], 35 [4, 2], [4, 3], [4, 5], [4, 7], [4, 8], [4, 10], 36 [5, 0], [5, 3], [5, 4], [5, 6], [5, 7], 37 [6, 5], [6, 7], 38 [7, 4], [7, 5], [7, 6], [7, 8], 39 [8, 4], [8, 7], [8, 9], [8, 10], [8, 11], 40 [9, 8], [9, 11], 41 [10, 2], [10, 4], [10, 8], [10, 11], 42 [11, 8], [11, 9], [11, 10] 43 ] from tkinter import * # Import tkinter 46 from GraphView import GraphView 47 from Graph import Graph window = Tk() # Create a window 50 window.title("us Map") # Set title graph = Graph(vertices, edges) 53 view = GraphView(graph, window, 750, 410) 54 view.pack() window.mainloop() # Create an event loop Figure

23 The graph is displayed on the canvas. The class City is defined to model the vertices with the coordinates and name (lines 3 19). The program creates a graph with the vertices of the City type (line 52). Since City extends Displayable, a GraphView object created for the graph displays the graph in the canvas (lines 53-54). As an exercise to get you acquainted with the graph classes and interfaces, add a city (e.g., Savannah) with appropriate edges into the graph Graph Traversals Key Point: Depth-first and breadth-first are two common ways to traverse a graph. Graph traversal is the process of visiting each vertex in the graph exactly once. There are two popular ways to traverse a graph: depth-first traversal (or depth-first search) and breadth-first traversal (or breadth-first search). Both traversals result in a spanning tree, which can be modeled using a class, as shown in Figure Tree root: int parent: list searchorders: list vertices: list Tree(root: int, parent: list, searchorders: list, vertices: list) getroot(): int getsearchorders(): list getparent(index: int): int getnumberofverticesfound(): int getpath(index: int): list printpath(index: int): None printtree(): None The root of the tree. The parents of the vertices in index. The orders for traversing the vertices in index. The vertices of the graph. Const ructs a tree wit h the specified root, parent, search orders, and vertices for the graph. Returns the root of the tree. Returns the order of vertices searched. Returns the parent for the specified vertex index. Returns the nu mber of vertices searched. Returns a list of vertices from the specified vertex index to the root. Displays a path from the root to the specified vertex. Displays tree with the root and all edges. Figure The Tree class describes the nodes with parent-child relationship. 23

24 The Tree class is defined in lines in Listing The constructor creates a tree with the root, edges, a search order, and vertices (lines ). The getroot() method returns the root of the tree (lines ). You can get the order of the vertices searched by invoking the getsearchorders() method (lines ). You can invoke getparent(index) to find the parent of vertex at the specified index (lines ). Invoking getnumberofverticesfound() returns the number of vertices searched (lines ). Invoking getpath(index) returns a list of vertices from the specified vertex index to the root (lines ). Invoking printpath(index) displays a path from the root to the specified vertex index (lines ). You can display all edges in the tree using the printtree() method (lines ). Sections 22.7 and 22.8 will introduce depth-first search and breadth-first search, respectively. Both searches will return an instance of the Tree class Depth-First Search (DFS) Key Point: The depth-first search of a graph first visits a vertex, then recursively visits all vertices adjacent to that vertex. The depth-first search of a graph is like the depth-first search of a tree discussed in , Tree Traversal. In the case of a tree, the search starts from the root. In a graph, the search can start from any vertex. A depth-first search of a tree first visits the root, then recursively visits the subtrees of the root. Similarly, the depth-first search of a graph first visits a vertex, then recursively visits all vertices adjacent to that vertex. The difference is that the graph may contain cycles, which may lead to an infinite recursion. To avoid this problem, you need to track the vertices that have already been visited. 24

25 The search is called depth-first, because it searches deeper in the graph as much as possible. The search starts from some vertex v. After visiting v, it next visits the first unvisited neighbor of v. If v has no unvisited neighbor, backtrack to the vertex from which we reached v Depth-First Search Algorithm The algorithm for the depth-first search can be described in Listing Listing 22.6 Depth-First Search Algorithm dfs(vertex v): visit v for each neighbor w of v: if w has not been visited: dfs(w) You may use a list named isvisited to denote whether a vertex has been visited. Initially, isvisited[i] is False for each vertex i. Once a vertex, say v, is visited, isvisited[v] is set to True. Consider the graph in Figure 22.11a. Suppose you start the depth-first search from vertex 0. First visit 0, then any of its neighbors, say 1. Now 1 is visited, as shown in Figure 22.11b. Vertex 1 has three neighbors 0, 2, and 4. Since 0 has already been visited, you will visit either 2 or 4. Let us pick 2. Now 2 is visited, as shown in Figure 22.11c. 2 has three neighbors 0, 1, and 3. Since 0 and 1 have already been visited, pick 3. 3 is now visited, as shown in Figure 22.11d. At this point, the vertices have been visited in this order: 0, 1, 2, 3 Since all the neighbors of 3 have been visited, backtrack to 2. Since all the vertices of 2 have been visited, backtrack to 1. 4 is adjacent to 1, but 4 has not been visited. So, visit 4, as shown in Figure 22.11e. Since all the neighbors of 4 have been visited, backtrack to 1. Since all the neighbors of 1 have been visited, backtrack to 0. Since all the neighbors of 0 have been visited, the search ends. 25

26 (a) (b) (c) (d) 3 4 (e) Figure Depth-first search visits a node and its neighbors recursively. Since each edge and each vertex is visited only once, the time complexity of the dfs method is O( E + V ), where E denotes the number of edges and V the number of vertices Implementation of Depth-First Search The algorithm is described in Listing 22.3 using recursion. It is natural to use recursion to implement it. The dfs(v) method is implemented in lines in Listing It returns an instance of the Tree class with vertex v as the root. The method stores the vertices searched in a list searchorders (line 63), the parent of each vertex in a list parent (line 64), and uses the isvisited list to indicate whether a vertex has been visited (line 67). It invokes the helper method dfshelper(v, parent, searchorders, isvisited) to perform a depth-first search (line 70). 26

27 In the recursive helper method, the search starts from vertex v. v is added to searchorders in line 78 and is marked visited (line 79). For each unvisited neighbor of v, the method is recursively invoked to perform a depth-first search. When a vertex i is visited, the parent of i is stored in parent[i] (line 83). The method returns when all vertices are visited for a connected graph, or in a connected component. Listing 22.7 gives a test program that displays a DFS for the graph in Figure 22.1 starting from Chicago. The graphical illustration of the DFS starting from Chicago is shown in Figure For an interactive GUI demo, see Listing 22.7 TestDFS.py 1 from Graph import Graph 2 from Graph import Tree 3 4 # Create vertices for graph in Figure vertices = ["Seattle", "San Francisco", "Los Angeles", 6 "Denver", "Kansas City", "Chicago", "Boston", "New York", 7 "Atlanta", "Miami", "Dallas", "Houston"] 8 9 # Create an edge list for graph in Figure edges = [ 11 [0, 1], [0, 3], [0, 5], 12 [1, 0], [1, 2], [1, 3], 13 [2, 1], [2, 3], [2, 4], [2, 10], 14 [3, 0], [3, 1], [3, 2], [3, 4], [3, 5], 15 [4, 2], [4, 3], [4, 5], [4, 7], [4, 8], [4, 10], 16 [5, 0], [5, 3], [5, 4], [5, 6], [5, 7], 17 [6, 5], [6, 7], 18 [7, 4], [7, 5], [7, 6], [7, 8], 19 [8, 4], [8, 7], [8, 9], [8, 10], [8, 11], 20 [9, 8], [9, 11], 21 [10, 2], [10, 4], [10, 8], [10, 11], 22 [11, 8], [11, 9], [11, 10] 23 ] graph = Graph(vertices, edges) dfs = graph.dfs(graph.getindex("chicago")) searchorders = dfs.getsearchorders() 30 print(str(dfs.getnumberofverticesfound()) + 31 " vertices are searched in this DFS order:") 32 for i in range(len(searchorders)): 33 print(graph.getvertex(searchorders[i]), end = " ") 34 print(); for i in range(len(searchorders)): 37 if dfs.getparent(i)!= -1: 38 print("parent of " + graph.getvertex(i) + 39 " is " + graph.getvertex(dfs.getparent(i))) 27

28 Sample output 12 vertices are searched in this DFS order: Chicago Seattle San Francisco Los Angeles Denver Kansas City New York Boston Atlanta Miami Houston Dallas parent of Seattle is Chicago parent of San Francisco is Seattle parent of Los Angeles is San Francisco parent of Denver is Los Angeles parent of Kansas City is Denver parent of Boston is New York parent of New York is Kansas City parent of Atlanta is New York parent of Miami is Atlanta parent of Dallas is Houston parent of Houston is Miami Figure DFS search starts from Chicago Applications of the DFS The depth-first search can be used to solve many problems, such as the following: Detecting whether a graph is connected. Search the graph starting from any vertex. If the number of vertices searched is the same as the number of vertices in the graph, the graph is connected. Otherwise, the graph is not connected. (See Exercise 22.1.) 28

29 Detecting whether there is a path between two vertices. (See Exercise 22.5.) Finding a path between two vertices. (See Exercise 22.5.) Finding all connected components. A connected component is a maximal connected subgraph in which every pair of vertices are connected by a path. (See Exercise 22.4.) Detecting whether there is a cycle in the graph. (See Exercise 22.6.) Finding a cycle in the graph. (See Exercise 22.7.) Finding a Hamiltonian path/cycle. A Hamiltonian path in a graph is a path that visits each vertex in the graph exactly once. A Hamiltonian cycle visits each vertex in the graph exactly once and returns to the starting vertex. The first five problems can be easily solved using the dfs method in Listing To find a Hamiltonian path/cycle, you have to explore all possible dfs and to find the one that leads the longest path. Hamiltonian path/cycle has many applications including for solving the well-known Knight s Tour problem, which is presented in the case study in the Companion Website Case Study: The Connected Circles Problem Key Point: The connected circles problem is to determine whether all circles in a two-dimensional plane are connected. This problem can be solved using a depth-first traversal. The DFS algorithm has many applications. This section applies the DFS to solve the connected circles problem. 29

30 The connected circles problem is to determine whether all circles in a two-dimensional plane are connected. If all circles are connected, they are painted as filled circles, as shown in Figure 22.13a. Otherwise, they are not filled, as shown in Figure 22.13b. (a) Circles are connected (b) Circles are not connected Figure You can apply DFS to determine whether the circles are connected. We will write a program that lets the user create a circle by clicking a mouse in a blank area that is not currently covered by a circle. As the circles are added, the circles are repainted filled if they are connected or unfilled otherwise. We will create a graph to model the problem. Each circle is a vertex in the graph. Two circles are connected if they overlap. We apply the DFS in the graph. If all vertices are found in the depth-first search, the graph is connected. The program is given in Listing Listing 22.8 ConnectedCircles.py 1 from tkinter import * # Import tkinter 2 from Graph import Graph 3 4 def add(event): 5 circles.append([event.x, event.y]) 6 repaint() 7 30

31 8 def distance(circle1, circle2): 9 return ((circle1[0] - circle2[0]) ** (circle1[1] - circle2[1]) ** 2) ** def repaint(): 13 canvas.delete("point") if len(circles) == 0: return # Nothing to paint # Build the edges 18 edges = [] 19 for i in range(len(circles)): 20 for j in range(i + 1, len(circles)): 21 if distance(circles[i], circles[j]) <= 2 * radius: 22 edges.append([i, j]) 23 edges.append([j, i]) graph = Graph(circles, edges) 26 tree = graph.dfs(0) 27 isallcirclesconnected = \ 28 len(circles) == tree.getnumberofverticesfound() for [x, y] in circles: 31 if isallcirclesconnected: # All circles are connected 32 canvas.create_oval(x - radius, y - radius, x + radius, 33 y + radius, fill = "red", tags = "point") 34 else: 35 canvas.create_oval(x - radius, y - radius, x + radius, 36 y + radius, tags = "point") window = Tk() # Create a window 39 window.title("connectedcircles") # Set title width = height = radius = canvas = Canvas(window, bg = "white", width = width, height = height) 45 canvas.pack() # Create a 2-D list for storing circles 48 circles = [] canvas.bind("<button-1>", add) window.mainloop() # Create an event loop When the user clicks the mouse, a new circle is created centered at the mouse point and the circle is added to a list circles (line 5). To detect whether the circles are connected, the program constructs a graph (lines 18-25). The circles are the vertices of the graph. The edges are constructed in lines Two circle vertices are connected if they overlapped (line 21). The DFS of the graph results in a tree (line 26). The tree s 31

32 getnumberofverticesfound() returns the number of vertices searched. If it is equal to the number of circles, all circles are connected (lines 27-28). The circles are repainted (lines 30-36). If all the circles are connected, the circles are filled with red (lines 32-33); otherwise, they are displayed without filling a color (lines 35-36) Breadth-First Search (BFS) Key Point: The breadth-first search of a graph first visits a vertex, then all its adjacent vertices, then all the vertices adjacent to those vertices, and so on. The breadth-first traversal of a graph is like the breadth-first traversal of a tree discussed in , Tree Traversal. With breadth-first traversal of a tree, the nodes are visited level by level. First the root is visited, then all the children of the root, then the grandchildren of the root, and so on. Similarly, the breadth-first search of a graph first visits a vertex, then all its adjacent vertices, then all the vertices adjacent to those vertices, and so on. To ensure that each vertex is visited only once, skip a vertex if it has already been visited Breadth-First Search Algorithm The algorithm for the breadth-first search starting from vertex v in a graph can be described in Listing Listing 22.9 Breadth-First Search Algorithm bfs(vertex v): create an empty queue for storing vertices to be visited add v into the queue mark v visited while the queue is not empty: dequeue a vertex, say u, from the queue add u into a list of traversed vertices for each neighbor w of u if w has not been visited: add w into the queue mark w visited 32

33 Consider the graph in Figure 22.14a. Suppose you start the breadth-first search from vertex 0. First visit 0, then all its visited neighbors, 1, 2, and 3, as shown in Figure 22.14b. Vertex 1 has three neighbors, 0, 2, and 4. Since 0 and 2 have already been visited, you will now visit just 4, as shown in Figure 22.14c. Vertex 2 has three neighbors, 0, 1, and 3, which are all visited. Vertex 3 has three neighbors, 0, 2, and 4, which are all visited. Vertex 4 has two neighbors, 1 and 3, which are all visited. So, the search ends (a) (b) (c) Figure Breadth-first search visits a node, then its neighbors, then its neighbors neighbors, and so on. Since each edge and each vertex is visited only once, the time complexity of the bfs method is O( E + V ), where E denotes the number of edges and V the number of vertices Implementation of Breadth-First Search The bfs(int v) method is implemented in the Graph (lines ) in Listing It returns an instance of the Tree class with vertex v as the root. The method stores the vertices searched in a list searchorders (line 90), the parent of each vertex in the parent list (line 91), uses a queue to store the vertices visited (line 93), and uses the isvisited list to indicate whether a vertex has been visited (line 94). The search starts from vertex v. v is added to the queue in line 95 and is marked visited (line 96). The method now examines each vertex u in the queue (line 99) and adds it to searchorders (line 100). The method adds each unvisited neighbor w of u to the queue (line 103), set its parent to u (line 104), and mark it visited (line 105). 33

34 Listing gives a test program that displays a BFS for the graph in Figure 22.1 starting from Chicago. The graphical illustration of the BFS starting from Chicago is shown in Figure For an interactive GUI demo, see Listing TestBFS.py 1 from Graph import Graph 2 from Graph import Tree 3 4 # Create vertices for graph in Figure vertices = ["Seattle", "San Francisco", "Los Angeles", 6 "Denver", "Kansas City", "Chicago", "Boston", "New York", 7 "Atlanta", "Miami", "Dallas", "Houston"] 8 9 # Create an edge list for graph in Figure edges = [ 11 [0, 1], [0, 3], [0, 5], 12 [1, 0], [1, 2], [1, 3], 13 [2, 1], [2, 3], [2, 4], [2, 10], 14 [3, 0], [3, 1], [3, 2], [3, 4], [3, 5], 15 [4, 2], [4, 3], [4, 5], [4, 7], [4, 8], [4, 10], 16 [5, 0], [5, 3], [5, 4], [5, 6], [5, 7], 17 [6, 5], [6, 7], 18 [7, 4], [7, 5], [7, 6], [7, 8], 19 [8, 4], [8, 7], [8, 9], [8, 10], [8, 11], 20 [9, 8], [9, 11], 21 [10, 2], [10, 4], [10, 8], [10, 11], 22 [11, 8], [11, 9], [11, 10] 23 ] graph = Graph(vertices, edges) 26 bfs = graph.bfs(graph.getindex("chicago")) searchorders = bfs.getsearchorders() 29 print(str(bfs.getnumberofverticesfound()) + 30 " vertices are searched in this order:") 31 for i in range(len(searchorders)): 32 print(graph.getvertex(searchorders[i]), end = " ") 33 print() for i in range(len(searchorders)): 36 if bfs.getparent(i)!= -1: 37 print("parent of " + graph.getvertex(i) + 38 " is " + graph.getvertex(bfs.getparent(i))) Sample output 12 vertices are searched in this order: Chicago Seattle Denver Kansas City Boston New York San Francisco Los Angeles Atlanta Dallas Miami Houston parent of Seattle is Chicago parent of San Francisco is Seattle parent of Los Angeles is Denver parent of Denver is Chicago parent of Kansas City is Chicago parent of Boston is Chicago 34

35 parent of New York is Chicago parent of Atlanta is Kansas City parent of Miami is Atlanta parent of Dallas is Kansas City parent of Houston is Atlanta Figure BFS search starts from Chicago Applications of the BFS Many of the problems solved by the DFS can also be solved using the BFS. Specifically, the BFS can be used to solve the following problems: Detecting whether a graph is connected. A graph is connected if there is a path between any two vertices in the graph. Detecting whether there is a path between two vertices. 35

36 Finding a shortest path between two vertices. You can prove that the path between the root and any node in the BFS tree is the shortest path between the root and the node. (See Review Question ) Finding all connected components. A connected component is a maximal connected subgraph in which every pair of vertices are connected by a path. Detecting whether there is a cycle in the graph. (See Exercise 22.6.) Finding a cycle in the graph. (See Exercise 22.7.) Testing whether a graph is bipartite. A graph is bipartite if the vertices of the graph can be divided into two disjoint sets such that no edges exist between vertices in the same set. (See Exercise 22.8.) Check point 22.5 Describe the relationships between the Graph and Tree classes defined in Listing What is the return type from invoking dfs(v) and bfs(v)? 22.7 What are depth-first search and breadth-first search? What a dfs tree is like for a complete graph? What a bfs tree is like for a complete graph? 22.8 How many edges are in a complete graph? How many edges are in a tree? 22.9 Show the DFS and BFS for the graph in Figure 22.1 starting from vertex Atlanta The depth-first search algorithm described in Listing 22.3 uses recursion. Alternatively you may use a stack to implement it, as shown below. Point out the error in this algorithm and give a correct algorithm. # Wrong version 36

37 dfs(vertex v: push v into the stack mark v visited while the stack is not empty: pop a vertex, say u, from the stack visit u for each neighbor w of u if (w has not been visited) push w into the stack Prove that the path between the root and any node in the BFS tree is the shortest path between the root and the node Case Study: The Nine Tail Problem Key Point: The Nine Tail problem can be reduced to the shortest path problem. The nine tail problem is stated as follows. Nine coins are placed in a three-by-three matrix with some face up and some face down. A legal move is to take any coin that is face up and reverse it, together with the coins adjacent to it (this does not include coins that are diagonally adjacent). Your task is to find the minimum number of moves that lead to all coins face down. For example, you start with the nine coins as shown in Figure 22.16a. After you flip the second coin in the last row, the nine coins are now as shown in Figure 22.16b. After you flip the second coin in the first row, the nine coins are all face down, as shown in Figure 22.16c. H H H T T T H H H H H H T H T T T T T T T T T T T T T (a) (b) (c) Figure The problem is solved when all coins are face down. We will write a program that prompts the user to enter an initial state of the nine coins and displays the solution, as shown in the following sample run. 37

38 Sample output Enter an initial nine coin H's and T's: HHHTTTHHH The steps to flip the coins are HHH TTT HHH HHH THT TTT TTT TTT TTT Each state of the nine coins represents a node in the graph. For example, the three states in Figure correspond to three nodes in the graph. For convenience, we use a 3 3 matrix to represent all nodes and use 0 for head and 1 for tail. Since there are nine cells and each cell is either 0 or 1, there are a total of 9 2 (512) nodes, labeled 0, 1,..., and 511, as shown in Figure Figure There are total of 512 nodes, labeled in this order as 0, 1, 2,..., 511. We assign an edge from node u to v if there is a legal move from v to u. Figure shows the directed edges to node

39 Figure If node v becomes node u after cells are flipped, assign an edge from u to v. The last node in Figure represents the state of nine face-down coins. For convenience, we call this last node the target node. So, the target node is labeled 511. Suppose the initial state of the nine tail problem corresponds to the node s. The problem is reduced to finding a shortest path from node s to the target node, which is equivalent to finding a path from node s to the target node in a BFS tree rooted at the target node. Now the task is to build a graph that consists of 512 nodes labeled 0, 1, 2,..., 511, and edges among the nodes. Once the graph is created, obtain a BFS tree rooted at node 511. From the BFS tree, you can find the shortest path from the root to any vertex. We will create a class named NineTailModel, which contains the method to get the shortest path from the target node to any other node. The class UML diagram is shown in Figure The class contains methods and also functions. The functions are underlined. Recalled that the methods are invoked from objects, but functions are invoked standalone. NineTailModel tree: Tree NineTailModel() getshortestpath(nodeindex: int): list getedges(): list getnode(index: int): list getindex(node: list): int getflippednode(n ode: list, position: int): int flip ACell(node: list, row: in t, colu mn: int): None printnode(node: list): None A tree rooted at node 511. Constructs a model for the nine tail problem and obtains the tree. Retu rns a path from the specified node to th e root. The path returned consists of the node labels in a list. Retu rns an edge list for the graph. Returns a node consisting of nine characters of H s and T s. Returns the index of the specified node. Flips the node at the specified position and returns the index of the flipped node. Flips the node at the specified row and column. Disp lays the node to the console. 39

40 Figure The NineTailModel class models the nine tail problem using a graph. Listing shows the source code for NineTailModel.py. Listing NineTailModel.py 1 from Graph import Graph 2 from Graph import Tree 3 4 NUMBER_OF_NODES = class NineTailModel: 6 def init (self): 7 edges = getedges(); 8 9 # Create a graph 10 vertices = [x for x in range(number_of_nodes)] 11 graph = Graph(vertices, edges) # Obtain a BSF tree rooted at the target node 14 self.tree = graph.bfs(511) def getshortestpath(self, nodeindex): 17 return self.tree.getpath(nodeindex) def printnode(node): 20 for i in range(9): 21 if i % 3!= 2: 22 print(node[i], end = " ") 23 else: 24 print(node[i]) print() # Create all edges for the graph 29 def getedges(): 30 edges = [] # Store edges 31 for u in range(number_of_nodes): 32 for k in range(9): 33 node = getnode(u) # Get the node for vertex u 34 if node[k] == 'H': 35 v = getflippednode(node, k) 36 # Add edge (v, u) for a legal move from node u to node v 37 edges.append([v, u]) return edges def getflippednode(node, position): 42 row = position // 3 43 column = position % flipacell(node, row, column) 46 flipacell(node, row - 1, column) 47 flipacell(node, row + 1, column) 48 flipacell(node, row, column - 1) 49 flipacell(node, row, column + 1) return getindex(node) 52 40

41 53 def getindex(node): 54 result = for i in range(9): 57 if node[i] == 'T': 58 result = result * else: 60 result = result * return result def flipacell(node, row, column): 65 if row >= 0 and row <= 2 and column >= 0 and column <= 2: 66 # Within the boundary 67 if node[row * 3 + column] == 'H': 68 node[row * 3 + column] = 'T' # Flip from H to T 69 else: 70 node[row * 3 + column] = 'H' # Flip from T to H def getnode(index): 73 result = 9 * [' '] for i in range(9): 76 digit = index % 2 77 if digit == 0: 78 result[8 - i] = 'H' 79 else: 80 result[8 - i] = 'T' 81 index = index // return result The constructor (lines 6 14) creates a graph with 512 nodes, and each edge corresponds to the move from one node to the other (line 7). From the graph, a BFS tree rooted at the target node 511 is obtained (line 14). To create edges, the getedges function (lines 29 39) checks each node u to see if it can be flipped to another node v. If so, add (v, u) to the edge adjacency list (line 37). The getflippednode(node, position) function (line 41) finds a flipped node by flipping an H cell and its neighbors in a node (lines 45 49). The flipacell(node, row, column) function actually flips an H cell and its neighbors in a node (lines 64 70). The getindex(node) function is implemented in the same way as converting a binary number to a decimal (lines 53 62). The getnode(index) function returns a node consisting of letters H and T s (lines 72 83). 41

42 The getshortestpath(nodeindex) method invokes the getpath(nodeindex) method to get the vertices in the shortest path from the specified node to the target node (lines 16 17). The printnode(node) function displays a node to the console (lines 19 26). Listing gives a program that prompts the user to enter an initial node and displays the steps to reach the target node. Listing NineTail.py 1 from NineTailModel import NineTailModel 2 from NineTailModel import getindex 3 from NineTailModel import getnode 4 from NineTailModel import printnode 5 6 def main(): 7 # Prompt the user to enter nine coins H's and T's 8 initialnode = \ 9 input("enter an initial nine coin H's and T's: ").strip() # Create the NineTaileModel 12 model = NineTailModel() 13 path = model.getshortestpath(getindex(initialnode)) print("the steps to flip the coins are "); 16 for i in range(len(path)): 17 printnode(getnode(path[i])) main() The program prompts the user to enter an initial node with nine letters, H s and T s, as a string in line 8, creates a model to create a graph and get the BFS tree (line 11), obtains a shortest path from the initial node to the target node (line 12), and displays the nodes in the path (lines 14 16). Check point What is returned after invoking getindex("hthttthhh") in Listing 22.7? What is returned after invoking getnode(46) in Listing 22.7? Key Terms 42

43 adjacency list adjacent vertices adjacency matrix breadth-first search complete graph degree depth-first search directed graph graph incident edges parallel edge Seven Bridges of Königsberg simple graph spanning tree weighted graph undirected graph unweighted graph Chapter Summary 1. A graph is a useful mathematical structure that represents relationships among entities in the real world. You learned how to model graphs using classes and interfaces, how to represent vertices and edges using lists of adjacency lists, and how to implement operations for vertices and edges. 2. Graph traversal is the process of visiting each vertex in the graph exactly once. You learned two popular ways for traversing a graph: depth-first search (DFS) and breadth-first search (BFS). 3. DFS and BFS can be used to solve many problems such as detecting whether a graph is connected, detecting whether there is a cycle in the graph, and finding a shortest path between two vertices. 43

44 Multiple-Choice Questions See multiple-choice questions online at liang.armstrong.edu/selftest/selftestpy?chapter=22. Programming Exercises Sections *22.1 (Test whether a graph is connected) Write a program that reads a graph from a file and determines whether the graph is connected. The first line in the file contains a number that indicates the number of vertices (n). The vertices are labeled as 0, 1,..., n-1. Each subsequent line, with the format u v1 v2..., describes edges (u, v1), (u, v2), and so on. Figure gives the examples of two files for their corresponding graphs. File File (a) (b) Figure The vertices and edges of a graph can be stored in a file. Your program should prompt the user to enter the name of the file, should read data from a file, create an instance g of Graph, invoke g.printedges() to display all edges, and invokes dfs() to obtain an instance tree of Tree. If tree.getnumberofverticefound() is the same as the number of vertices in the graph, the graph is connected. Here is a sample run of the program: Sample output 44

45 Enter a file name: c:\exercise\exercise22_1a.txt The number of vertices is 6 Vertex 0: (0, 1) (0, 2) Vertex 1: (1, 0) (1, 3) Vertex 2: (2, 0) (2, 3) (2, 4) Vertex 3: (3, 1) (3, 2) (3, 4) (3, 5) Vertex 4: (4, 2) (4, 3) (4, 5) Vertex 5: (5, 3) (5, 4) The graph is connected *22.2 (Create a file for a graph) Modify Listing 22.1, TestGraph.py, to create a file for representing graph1. The file format is described in Exercise Create the file from the list defined in lines 8-21 in Listing The number of vertices for the graph is 12, which will be stored in the first line of the file. The contents of the file should be as follows: *22.3 (Implement DFS using a stack) The depth-first search algorithm described in Listing 22.3 uses recursion. Implement it without using recursion. *22.4 (Find connected components) Create a new class named MyGraph as a subclass of UnweightedGraph that contains a method for finding all connected components in a graph with the following header: def getconnectedcomponents(): The method returns a list. Each element in the list is another list that contains all the vertices in a connected component. For example, for the graph in Figure 22.20b, getconnectedcomponents() returns [[0, 1, 2, 3], [4, 5]]. 45

46 *22.5 (Find paths) Add a new method in the Graph class to find a path between two vertices with the following header: def getpath(u, v): The method returns a list of integers that contains all the vertices in a path from u to v in this order. Using the BFS approach, you can obtain a shortest path from u to v. If there is no path from u to v, the method returns None. *22.6 (Detect cycles) Add a new method in Graph to determine whether there is a cycle in the graph with the following header: def iscyclic(): *22.7 (Find a cycle) Add a new method in Graph to find a cycle in the graph with the following header: def getacycle() The method returns a list that contains all the vertices in a cycle from u to v in this order. If the graph has no cycles, the method returns None. **22.8 (Test bipartite) Recall that a graph is bipartite if its vertices can be divided into two disjoint sets such that no edges exist between vertices in the same set. Add a new method in Graph to detect whether the graph is bipartite: def isbipartite(): **22.9 (Get bipartite sets) Add a new method in Graph to return two bipartite sets if the graph is bipartite: def getbipartite(): The method returns a list that contains two sublists, each of which contains a set of vertices. If the graph is not bipartite, the method returns None. *22.10 (Find a shortest path) Write a program that reads a connected graph from a file. The graph is stored in a file using the same format specified in Exercise Your program should prompt 46

47 the user to enter the name of the file, then two vertices, and should display the shortest path between the two vertices. For example, for the graph in Figure 22.20a, a shortest path between 0 and 5 may be displayed as Here is a sample run of the program: Sample output Enter a file name: c:\exercise\exercise22_1a.txt Enter two vertices (integer indexes): 0, 5 The number of vertices is 6 Vertex 0: (0, 1) (0, 2) Vertex 1: (1, 0) (1, 3) Vertex 2: (2, 0) (2, 3) (2, 4) Vertex 3: (3, 1) (3, 2) (3, 4) (3, 5) Vertex 4: (4, 2) (4, 3) (4, 5) Vertex 5: (5, 3) (5, 4) The path is **22.11 (Variation of the nine tail problem) In the nine tail problem, when you flip a head, the horizontal and vertical neighboring cells are also flipped. Rewrite the program, assuming that all neighboring cells including the diagonal neighbors are also flipped. **22.12 ( tail model) The nine tail problem in the text uses a 3 3 matrix. Assume that you have 16 coins placed in a 4 4 matrix. Create a new model class named TailModel22. Create an instance of the model and save the object into a file named Exercise22_12.dat. **22.13 (Induced subgraph) Given an undirected graph G = (V, E) and an integer k, find an induced subgraph H of G of maximum size such that all vertices of H have degree >= k, or conclude that no such induced subgraph exists. Implement the method with the following header: def maxinducedsubgraph(edge, k): 47

48 The method returns None if such subgraph does not exist. (Hint: An intuitive approach is to remove vertices whose degree is less than k. As vertices are removed with their adjacent edges, the degrees of other vertices may be reduced. Continue the process until no vertices can be removed, or all the vertices are removed.) (Hamiltonian cycle) The Hamiltonian path algorithm was implemented in Supplement VII.C. Add the following gethamiltoniancycle method in the Graph class: # Return a Hamiltonian cycle # Return None if the graph contains no Hamiltonian cycle def gethamiltoniancycle(): **22.15 (Display sets of connected circles) Modify Listing 22.8, ConnectedCircles.py, to display sets of connected circles in different colors, i.e., if two circles are connected, they are displayed using the same color; otherwise, they are not in same color, as shown in Figure (Hint: see Exercise 22.4) (a) (b) (c) Figure (a) Connected circles are displayed in the same color. (b-c) Rectangles are filled with a color if they are connected. *22.16(Move a circle) Modify Listing 22.8, ConnectedCircles.py, to enable the user to drag and move a circle. 48

49 **22.17 (Connected rectangles) Listing 22.8, ConnectedCircles.py, allows the user to create circles and determine whether they are connected. Rewrite the program for rectangles. The program lets the user create a rectangle by clicking a mouse in a blank area that is not currently covered by a rectangle. As the rectangles are added, the rectangles are repainted filled if they are connected or unfilled otherwise, as shown in Figure 22.21b-c. *22.18 (Removing a circle) Modify Listing 22.8, ConnectedCircles.py, to enable the user to remove a circle when the mouse is clicked inside the circle. **22.19 (Revise Listing 22.8, NineTail.py) The program in Listing 22.8 lets the user enter an input for the nine tail program from the console and displays the result on the console. Write a GUI program that lets the user set an initial state of the nine coins (see Figure 22.22a) and click the Solve button to display the solution, as shown in Figure 22.22b. Initially, the user can click the mouse button to flip a coin. (a) (b) Figure The program solves the nine tail problem. *22.20 (Display a graph) Write a program that reads a graph from a file and displays it. The first line in the file contains a number that indicates the number of vertices (n). The vertices are labeled 0, 1,..., n-1. Each subsequent line, with the format u x y v1 v2..., describes the position of u at (x, y) and edges (u, v1), (u, v2), and so on. Figure 22.23a gives an example of the file for their corresponding graph. Your program prompts the user to enter the name of 49

50 the file, reads data from a file, and displays the graph on a panel using GraphView, as shown in Figure 22.23b. File (a) (b) 6 Figure The program reads the information about the graph and displays it visually. ***22.21 (Graph visualization tool) Develop a GUI program as shown in Figure 22.4, with the following requirements: (1) The radius of each vertex is 20 pixels. (2) The user clicks the left-mouse button to place a vertex centered at the mouse point provided that the mouse point is not inside or too close to an existing vertex. (3) The user clicks the right-mouse button inside an existing vertex to remove the vertex. (4) The user presses a mouse button inside a vertex and drags to another vertex and then releases the button to create an edge. (5) The user drags a vertex while pressing the CTRL key to move a vertex. (6) The vertices are numbers starting from 0. When a vertex is removed, the vertices are renumbered. (7) You can click the DFS or BFS button to display a DFS or BFS tree from a starting vertex. (8) You can click the Shortest Path button to display the shortest path between the two specified vertices. 50

To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem

To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem CHAPTER 24 Graphs and Applications Objectives To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem ( 24.1). To describe graph terminologies: vertices, edges, simple

More information

GRAPHS AND APPLICATIONS

GRAPHS AND APPLICATIONS CHAPTER 3 GRAPHS AND APPLICATIONS Objectives To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem ( 3.). To describe the graph terminologies: vertices, edges, simple

More information

Chapter 28 Graphs and Applications. Objectives

Chapter 28 Graphs and Applications. Objectives Chapter 28 Graphs and Applications CS2: Data Structures and Algorithms Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox, Wim Bohm, and Russ Wakefield 1 Objectives

More information

Chapter 28. Graphs and Applications. Part1. Non-weighted Graphs

Chapter 28. Graphs and Applications. Part1. Non-weighted Graphs Chapter 28 Graphs and Applications Part1. Non-weighted Graphs CIS265/506 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

To represent weighted edges using adjacency matrices and adjacency lists ( 25.2).

To represent weighted edges using adjacency matrices and adjacency lists ( 25.2). CHAPTER Weighted Graphs and Applications Objectives To represent weighted edges using adjacency matrices and adjacency lists (.). To model weighted graphs using the WeightedGraph class that extends the

More information

Konigsberg Bridge Problem

Konigsberg Bridge Problem Graphs Konigsberg Bridge Problem c C d g A Kneiphof e D a B b f c A C d e g D a b f B Euler s Graph Degree of a vertex: the number of edges incident to it Euler showed that there is a walk starting at

More information

Worksheet for the Final Exam - Part I. Graphs

Worksheet for the Final Exam - Part I. Graphs Worksheet for the Final Exam - Part I. Graphs Date and Time: May 10 2012 Thursday 11:50AM~1:50PM Location: Eng 120 Start with the Self-Test Exercises (pp.816) in Prichard. 1. Give the adjacency matrix

More information

CS 220: Discrete Structures and their Applications. graphs zybooks chapter 10

CS 220: Discrete Structures and their Applications. graphs zybooks chapter 10 CS 220: Discrete Structures and their Applications graphs zybooks chapter 10 directed graphs A collection of vertices and directed edges What can this represent? undirected graphs A collection of vertices

More information

Understand graph terminology Implement graphs using

Understand graph terminology Implement graphs using raphs Understand graph terminology Implement graphs using djacency lists and djacency matrices Perform graph searches Depth first search Breadth first search Perform shortest-path algorithms Disjkstra

More information

CS 310 Advanced Data Structures and Algorithms

CS 310 Advanced Data Structures and Algorithms CS 31 Advanced Data Structures and Algorithms Graphs July 18, 17 Tong Wang UMass Boston CS 31 July 18, 17 1 / 4 Graph Definitions Graph a mathematical construction that describes objects and relations

More information

Graph Theory CS/Math231 Discrete Mathematics Spring2015

Graph Theory CS/Math231 Discrete Mathematics Spring2015 1 Graphs Definition 1 A directed graph (or digraph) G is a pair (V, E), where V is a finite set and E is a binary relation on V. The set V is called the vertex set of G, and its elements are called vertices

More information

Chapter 11: Graphs and Trees. March 23, 2008

Chapter 11: Graphs and Trees. March 23, 2008 Chapter 11: Graphs and Trees March 23, 2008 Outline 1 11.1 Graphs: An Introduction 2 11.2 Paths and Circuits 3 11.3 Matrix Representations of Graphs 4 11.5 Trees Graphs: Basic Definitions Informally, a

More information

CHAPTER 10 GRAPHS AND TREES. Alessandro Artale UniBZ - artale/z

CHAPTER 10 GRAPHS AND TREES. Alessandro Artale UniBZ -  artale/z CHAPTER 10 GRAPHS AND TREES Alessandro Artale UniBZ - http://www.inf.unibz.it/ artale/z SECTION 10.1 Graphs: Definitions and Basic Properties Copyright Cengage Learning. All rights reserved. Graphs: Definitions

More information

Grade 7/8 Math Circles Graph Theory - Solutions October 13/14, 2015

Grade 7/8 Math Circles Graph Theory - Solutions October 13/14, 2015 Faculty of Mathematics Waterloo, Ontario N2L 3G1 Centre for Education in Mathematics and Computing Grade 7/8 Math Circles Graph Theory - Solutions October 13/14, 2015 The Seven Bridges of Königsberg In

More information

Figure 1: A directed graph.

Figure 1: A directed graph. 1 Graphs A graph is a data structure that expresses relationships between objects. The objects are called nodes and the relationships are called edges. For example, social networks can be represented as

More information

Algorithms: Lecture 10. Chalmers University of Technology

Algorithms: Lecture 10. Chalmers University of Technology Algorithms: Lecture 10 Chalmers University of Technology Today s Topics Basic Definitions Path, Cycle, Tree, Connectivity, etc. Graph Traversal Depth First Search Breadth First Search Testing Bipartatiness

More information

STRUCTURES AND STRATEGIES FOR STATE SPACE SEARCH

STRUCTURES AND STRATEGIES FOR STATE SPACE SEARCH Slide 3.1 3 STRUCTURES AND STRATEGIES FOR STATE SPACE SEARCH 3.0 Introduction 3.1 Graph Theory 3.2 Strategies for State Space Search 3.3 Using the State Space to Represent Reasoning with the Predicate

More information

12/5/17. trees. CS 220: Discrete Structures and their Applications. Trees Chapter 11 in zybooks. rooted trees. rooted trees

12/5/17. trees. CS 220: Discrete Structures and their Applications. Trees Chapter 11 in zybooks. rooted trees. rooted trees trees CS 220: Discrete Structures and their Applications A tree is an undirected graph that is connected and has no cycles. Trees Chapter 11 in zybooks rooted trees Rooted trees. Given a tree T, choose

More information

Chapter 14. Graphs Pearson Addison-Wesley. All rights reserved 14 A-1

Chapter 14. Graphs Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs 2011 Pearson Addison-Wesley. All rights reserved 14 A-1 Terminology G = {V, E} A graph G consists of two sets A set V of vertices, or nodes A set E of edges A subgraph Consists of a subset

More information

CS/COE 1501 cs.pitt.edu/~bill/1501/ Graphs

CS/COE 1501 cs.pitt.edu/~bill/1501/ Graphs CS/COE 1501 cs.pitt.edu/~bill/1501/ Graphs 5 3 2 4 1 0 2 Graphs A graph G = (V, E) Where V is a set of vertices E is a set of edges connecting vertex pairs Example: V = {0, 1, 2, 3, 4, 5} E = {(0, 1),

More information

Scribes: Romil Verma, Juliana Cook (2015), Virginia Williams, Date: May 1, 2017 and Seth Hildick-Smith (2016), G. Valiant (2017), M.

Scribes: Romil Verma, Juliana Cook (2015), Virginia Williams, Date: May 1, 2017 and Seth Hildick-Smith (2016), G. Valiant (2017), M. Lecture 9 Graphs Scribes: Romil Verma, Juliana Cook (2015), Virginia Williams, Date: May 1, 2017 and Seth Hildick-Smith (2016), G. Valiant (2017), M. Wootters (2017) 1 Graphs A graph is a set of vertices

More information

GRAPHICAL ALGORITHMS. UNIT _II Lecture-12 Slides No. 3-7 Lecture Slides No Lecture Slides No

GRAPHICAL ALGORITHMS. UNIT _II Lecture-12 Slides No. 3-7 Lecture Slides No Lecture Slides No GRAPHICAL ALGORITHMS UNIT _II Lecture-12 Slides No. 3-7 Lecture-13-16 Slides No. 8-26 Lecture-17-19 Slides No. 27-42 Topics Covered Graphs & Trees ( Some Basic Terminologies) Spanning Trees (BFS & DFS)

More information

Algorithm Design and Analysis

Algorithm Design and Analysis Algorithm Design and Analysis LECTURE 5 Exploring graphs Adam Smith 9/5/2008 A. Smith; based on slides by E. Demaine, C. Leiserson, S. Raskhodnikova, K. Wayne Puzzles Suppose an undirected graph G is connected.

More information

Algorithm Design and Analysis

Algorithm Design and Analysis Algorithm Design and Analysis LECTURE 4 Graphs Definitions Traversals Adam Smith 9/8/10 Exercise How can you simulate an array with two unbounded stacks and a small amount of memory? (Hint: think of a

More information

Graph. Vertex. edge. Directed Graph. Undirected Graph

Graph. Vertex. edge. Directed Graph. Undirected Graph Module : Graphs Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS E-mail: natarajan.meghanathan@jsums.edu Graph Graph is a data structure that is a collection

More information

Graph Theory. Many problems are mapped to graphs. Problems. traffic VLSI circuits social network communication networks web pages relationship

Graph Theory. Many problems are mapped to graphs. Problems. traffic VLSI circuits social network communication networks web pages relationship Graph Graph Usage I want to visit all the known famous places starting from Seoul ending in Seoul Knowledge: distances, costs Find the optimal(distance or cost) path Graph Theory Many problems are mapped

More information

Trees. Arash Rafiey. 20 October, 2015

Trees. Arash Rafiey. 20 October, 2015 20 October, 2015 Definition Let G = (V, E) be a loop-free undirected graph. G is called a tree if G is connected and contains no cycle. Definition Let G = (V, E) be a loop-free undirected graph. G is called

More information

UNIT IV -NON-LINEAR DATA STRUCTURES 4.1 Trees TREE: A tree is a finite set of one or more nodes such that there is a specially designated node called the Root, and zero or more non empty sub trees T1,

More information

Foundations of Discrete Mathematics

Foundations of Discrete Mathematics Foundations of Discrete Mathematics Chapter 12 By Dr. Dalia M. Gil, Ph.D. Trees Tree are useful in computer science, where they are employed in a wide range of algorithms. They are used to construct efficient

More information

Crossing bridges. Crossing bridges Great Ideas in Theoretical Computer Science. Lecture 12: Graphs I: The Basics. Königsberg (Prussia)

Crossing bridges. Crossing bridges Great Ideas in Theoretical Computer Science. Lecture 12: Graphs I: The Basics. Königsberg (Prussia) 15-251 Great Ideas in Theoretical Computer Science Lecture 12: Graphs I: The Basics February 22nd, 2018 Crossing bridges Königsberg (Prussia) Now Kaliningrad (Russia) Is there a way to walk through the

More information

Depth-First Search Depth-first search (DFS) is another way to traverse the graph.

Depth-First Search Depth-first search (DFS) is another way to traverse the graph. Depth-First Search Depth-first search (DFS) is another way to traverse the graph. Motivating example: In a video game, you are searching for a path from a point in a maze to the exit. The maze can be modeled

More information

國立清華大學電機工程學系. Outline

國立清華大學電機工程學系. Outline 國立清華大學電機工程學系 EE Data Structure Chapter Graph (Part I) Outline The Graph Abstract Data Type Introduction Definitions Graph Representations Elementary Graph Operations Minimum Cost Spanning Trees ch.- River

More information

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology Trees : Part Section. () (2) Preorder, Postorder and Levelorder Traversals Definition: A tree is a connected graph with no cycles Consequences: Between any two vertices, there is exactly one unique path

More information

CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory

CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory Dustin Tseng Mike Li Wednesday January 16, 2006 Dustin Tseng Mike Li: CS490: Problem Solving in Computer Science, Lecture

More information

Graph Search Methods. Graph Search Methods

Graph Search Methods. Graph Search Methods Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u. 0 Graph Search Methods A search method starts at a given vertex v and visits/labels/marks every vertex that is

More information

Introduction III. Graphs. Motivations I. Introduction IV

Introduction III. Graphs. Motivations I. Introduction IV Introduction I Graphs Computer Science & Engineering 235: Discrete Mathematics Christopher M. Bourke cbourke@cse.unl.edu Graph theory was introduced in the 18th century by Leonhard Euler via the Königsberg

More information

(Refer Slide Time: 02.06)

(Refer Slide Time: 02.06) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 27 Depth First Search (DFS) Today we are going to be talking

More information

Today s Outline. CSE 326: Data Structures. Topic #15: Cool Graphs n Pretty Pictures. A Great Mathematician. The Bridges of Königsberg

Today s Outline. CSE 326: Data Structures. Topic #15: Cool Graphs n Pretty Pictures. A Great Mathematician. The Bridges of Königsberg CSE 326: Data Structures Topic #15: Cool Graphs n Pretty Pictures Ashish Sabharwal Autumn, 2003 Today s Outline Admin Project 3 in-progress checkin due tonight! Graph Algorithms Representation Applications

More information

Graph Theory. 1 Introduction to Graphs. Martin Stynes Department of Mathematics, UCC January 26, 2011

Graph Theory. 1 Introduction to Graphs. Martin Stynes Department of Mathematics, UCC   January 26, 2011 Graph Theory Martin Stynes Department of Mathematics, UCC email: m.stynes@ucc.ie January 26, 2011 1 Introduction to Graphs 1 A graph G = (V, E) is a non-empty set of nodes or vertices V and a (possibly

More information

CSE 100: GRAPH ALGORITHMS

CSE 100: GRAPH ALGORITHMS CSE 100: GRAPH ALGORITHMS 2 Graphs: Example A directed graph V5 V = { V = E = { E Path: 3 Graphs: Definitions A directed graph V5 V6 A graph G = (V,E) consists of a set of vertices V and a set of edges

More information

How can we lay cable at minimum cost to make every telephone reachable from every other? What is the fastest route between two given cities?

How can we lay cable at minimum cost to make every telephone reachable from every other? What is the fastest route between two given cities? 1 Introduction Graph theory is one of the most in-demand (i.e. profitable) and heavily-studied areas of applied mathematics and theoretical computer science. May graph theory questions are applied in this

More information

Chapter 9. Priority Queue

Chapter 9. Priority Queue Chapter 9 Priority Queues, Heaps, Graphs Spring 2015 1 Priority Queue Priority Queue An ADT in which only the item with the highest priority can be accessed 2Spring 2015 Priority Depends on the Application

More information

Section 3.4 Basic Results of Graph Theory

Section 3.4 Basic Results of Graph Theory 1 Basic Results of Graph Theory Section 3.4 Basic Results of Graph Theory Purpose of Section: To formally introduce the symmetric relation of a (undirected) graph. We introduce such topics as Euler Tours,

More information

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II CS 206 Introduction to Computer Science II 04 / 06 / 2018 Instructor: Michael Eckmann Today s Topics Questions? Comments? Graphs Definition Terminology two ways to represent edges in implementation traversals

More information

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F)) DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES UNIT IV NONLINEAR DATA STRUCTURES Part A 1. Define Tree [N/D 08]

More information

Graphs & Digraphs Tuesday, November 06, 2007

Graphs & Digraphs Tuesday, November 06, 2007 Graphs & Digraphs Tuesday, November 06, 2007 10:34 PM 16.1 Directed Graphs (digraphs) like a tree but w/ no root node & no guarantee of paths between nodes consists of: nodes/vertices - a set of elements

More information

Elementary Graph Algorithms. Ref: Chapter 22 of the text by Cormen et al. Representing a graph:

Elementary Graph Algorithms. Ref: Chapter 22 of the text by Cormen et al. Representing a graph: Elementary Graph Algorithms Ref: Chapter 22 of the text by Cormen et al. Representing a graph: Graph G(V, E): V set of nodes (vertices); E set of edges. Notation: n = V and m = E. (Vertices are numbered

More information

Chapter 2 Graphs. 2.1 Definition of Graphs

Chapter 2 Graphs. 2.1 Definition of Graphs Chapter 2 Graphs Abstract Graphs are discrete structures that consist of vertices and edges connecting some of these vertices. Graphs have many applications in Mathematics, Computer Science, Engineering,

More information

CS2 Algorithms and Data Structures Note 9

CS2 Algorithms and Data Structures Note 9 CS2 Algorithms and Data Structures Note 9 Graphs The remaining three lectures of the Algorithms and Data Structures thread will be devoted to graph algorithms. 9.1 Directed and Undirected Graphs A graph

More information

W4231: Analysis of Algorithms

W4231: Analysis of Algorithms W4231: Analysis of Algorithms 10/21/1999 Definitions for graphs Breadth First Search and Depth First Search Topological Sort. Graphs AgraphG is given by a set of vertices V and a set of edges E. Normally

More information

Discrete Mathematics for CS Spring 2008 David Wagner Note 13. An Introduction to Graphs

Discrete Mathematics for CS Spring 2008 David Wagner Note 13. An Introduction to Graphs CS 70 Discrete Mathematics for CS Spring 2008 David Wagner Note 13 An Introduction to Graphs Formulating a simple, precise specification of a computational problem is often a prerequisite to writing a

More information

GRAPHS (Undirected) Graph: Set of objects with pairwise connections. Why study graph algorithms?

GRAPHS (Undirected) Graph: Set of objects with pairwise connections. Why study graph algorithms? GRAPHS (Undirected) Graph: Set of objects with pairwise connections. Why study graph algorithms? Interesting and broadly useful abstraction. Challenging branch of computer science and discrete math. Hundreds

More information

Searching in Graphs (cut points)

Searching in Graphs (cut points) 0 November, 0 Breath First Search (BFS) in Graphs In BFS algorithm we visit the verices level by level. The BFS algorithm creates a tree with root s. Once a node v is discovered by BFS algorithm we put

More information

Outline. Graphs. Divide and Conquer.

Outline. Graphs. Divide and Conquer. GRAPHS COMP 321 McGill University These slides are mainly compiled from the following resources. - Professor Jaehyun Park slides CS 97SI - Top-coder tutorials. - Programming Challenges books. Outline Graphs.

More information

implementing the breadth-first search algorithm implementing the depth-first search algorithm

implementing the breadth-first search algorithm implementing the depth-first search algorithm Graph Traversals 1 Graph Traversals representing graphs adjacency matrices and adjacency lists 2 Implementing the Breadth-First and Depth-First Search Algorithms implementing the breadth-first search algorithm

More information

Graphs. Data Structures 1 Graphs

Graphs. Data Structures 1 Graphs Graphs Graph Applications Definitions Graph Representations(adjacency matrix/list) Graph ADT Graph Traversals: BFS, DFS Shortest Path Algorithms Minimum Spanning Tree Algorithms Data Structures Graphs

More information

Lecture 9 Graph Traversal

Lecture 9 Graph Traversal Lecture 9 Graph Traversal Euiseong Seo (euiseong@skku.edu) SWE00: Principles in Programming Spring 0 Euiseong Seo (euiseong@skku.edu) Need for Graphs One of unifying themes of computer science Closely

More information

COT 6405 Introduction to Theory of Algorithms

COT 6405 Introduction to Theory of Algorithms COT 6405 Introduction to Theory of Algorithms Topic 14. Graph Algorithms 11/7/2016 1 Elementary Graph Algorithms How to represent a graph? Adjacency lists Adjacency matrix How to search a graph? Breadth-first

More information

Graphs Introduction and Depth first algorithm

Graphs Introduction and Depth first algorithm Graphs Introduction and Depth first algorithm Carol Zander Introduction to graphs Graphs are extremely common in computer science applications because graphs are common in the physical world. Everywhere

More information

The Konigsberg Bridge Problem

The Konigsberg Bridge Problem The Konigsberg Bridge Problem This is a classic mathematical problem. There were seven bridges across the river Pregel at Königsberg. Is it possible to take a walk in which each bridge is crossed exactly

More information

MAT 7003 : Mathematical Foundations. (for Software Engineering) J Paul Gibson, A207.

MAT 7003 : Mathematical Foundations. (for Software Engineering) J Paul Gibson, A207. MAT 7003 : Mathematical Foundations (for Software Engineering) J Paul Gibson, A207 paul.gibson@it-sudparis.eu http://www-public.it-sudparis.eu/~gibson/teaching/mat7003/ Graphs and Trees http://www-public.it-sudparis.eu/~gibson/teaching/mat7003/l2-graphsandtrees.pdf

More information

CSI 604 Elementary Graph Algorithms

CSI 604 Elementary Graph Algorithms CSI 604 Elementary Graph Algorithms Ref: Chapter 22 of the text by Cormen et al. (Second edition) 1 / 25 Graphs: Basic Definitions Undirected Graph G(V, E): V is set of nodes (or vertices) and E is the

More information

Logic: The Big Picture. Axiomatizing Arithmetic. Tautologies and Valid Arguments. Graphs and Trees

Logic: The Big Picture. Axiomatizing Arithmetic. Tautologies and Valid Arguments. Graphs and Trees Axiomatizing Arithmetic Logic: The Big Picture Suppose we restrict the domain to the natural numbers, and allow only the standard symbols of arithmetic (+,, =, >, 0, 1). Typical true formulas include:

More information

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 Asymptotics, Recurrence and Basic Algorithms 1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 1. O(logn) 2. O(n) 3. O(nlogn) 4. O(n 2 ) 5. O(2 n ) 2. [1 pt] What is the solution

More information

Outlines: Graphs Part-2

Outlines: Graphs Part-2 Elementary Graph Algorithms PART-2 1 Outlines: Graphs Part-2 Graph Search Methods Breadth-First Search (BFS): BFS Algorithm BFS Example BFS Time Complexity Output of BFS: Shortest Path Breath-First Tree

More information

Lecture 3: Graphs and flows

Lecture 3: Graphs and flows Chapter 3 Lecture 3: Graphs and flows Graphs: a useful combinatorial structure. Definitions: graph, directed and undirected graph, edge as ordered pair, path, cycle, connected graph, strongly connected

More information

CS 3410 Ch 14 Graphs and Paths

CS 3410 Ch 14 Graphs and Paths CS 3410 Ch 14 Graphs and Paths Sections 14.1-14.3 Pages 527-552 Exercises 1,2,5,7-9 14.1 Definitions 1. A vertex (node) and an edge are the basic building blocks of a graph. Two vertices, (, ) may be connected

More information

CS/COE

CS/COE CS/COE 151 www.cs.pitt.edu/~lipschultz/cs151/ Graphs 5 3 2 4 1 Graphs A graph G = (V, E) Where V is a set of vertices E is a set of edges connecting vertex pairs Example: V = {, 1, 2, 3, 4, 5} E = {(,

More information

UNIT Name the different ways of representing a graph? a.adjacencymatrix b. Adjacency list

UNIT Name the different ways of representing a graph? a.adjacencymatrix b. Adjacency list UNIT-4 Graph: Terminology, Representation, Traversals Applications - spanning trees, shortest path and Transitive closure, Topological sort. Sets: Representation - Operations on sets Applications. 1. Name

More information

Graph Traversals. CS200 - Graphs 1

Graph Traversals. CS200 - Graphs 1 Graph Traversals CS200 - Graphs 1 Tree traversal reminder A Pre order A B D G H C E F I B C In order G D H B A E C F I D E F Post order G H D B E I F C A G H I Level order A B C D E F G H I Connected Components

More information

(Re)Introduction to Graphs and Some Algorithms

(Re)Introduction to Graphs and Some Algorithms (Re)Introduction to Graphs and Some Algorithms Graph Terminology (I) A graph is defined by a set of vertices V and a set of edges E. The edge set must work over the defined vertices in the vertex set.

More information

Graph Algorithms. Chapter 22. CPTR 430 Algorithms Graph Algorithms 1

Graph Algorithms. Chapter 22. CPTR 430 Algorithms Graph Algorithms 1 Graph Algorithms Chapter 22 CPTR 430 Algorithms Graph Algorithms Why Study Graph Algorithms? Mathematical graphs seem to be relatively specialized and abstract Why spend so much time and effort on algorithms

More information

Goals! CSE 417: Algorithms and Computational Complexity!

Goals! CSE 417: Algorithms and Computational Complexity! Goals! CSE : Algorithms and Computational Complexity! Graphs: defns, examples, utility, terminology! Representation: input, internal! Traversal: Breadth- & Depth-first search! Three Algorithms:!!Connected

More information

GRAPH THEORY AND COMBINATORICS ( Common to CSE and ISE ) UNIT 1

GRAPH THEORY AND COMBINATORICS ( Common to CSE and ISE ) UNIT 1 GRAPH THEORY AND COMBINATORICS ( Common to CSE and ISE ) Sub code : 06CS42 UNIT 1 Introduction to Graph Theory : Definition and Examples Subgraphs Complements, and Graph Isomorphism Vertex Degree, Euler

More information

Discrete Mathematics and Probability Theory Fall 2009 Satish Rao,David Tse Note 8

Discrete Mathematics and Probability Theory Fall 2009 Satish Rao,David Tse Note 8 CS 70 Discrete Mathematics and Probability Theory Fall 2009 Satish Rao,David Tse Note 8 An Introduction to Graphs Formulating a simple, precise specification of a computational problem is often a prerequisite

More information

Introduction to Graphs. CS2110, Spring 2011 Cornell University

Introduction to Graphs. CS2110, Spring 2011 Cornell University Introduction to Graphs CS2110, Spring 2011 Cornell University A graph is a data structure for representing relationships. Each graph is a set of nodes connected by edges. Synonym Graph Hostile Slick Icy

More information

Discrete Mathematics and Probability Theory Fall 2013 Vazirani Note 7

Discrete Mathematics and Probability Theory Fall 2013 Vazirani Note 7 CS 70 Discrete Mathematics and Probability Theory Fall 2013 Vazirani Note 7 An Introduction to Graphs A few centuries ago, residents of the city of Königsberg, Prussia were interested in a certain problem.

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Topic: Graphs - Introduction Kostas Alexis Terminology In the context of our course, graphs represent relations among data items G = {V,E} A graph is a set of vertices

More information

Announcements Problem Set 4 is out!

Announcements Problem Set 4 is out! CSC263 Week 8 Announcements Problem Set 4 is out! Due Tuesday (Nov 17) Other Announcements Drop date Nov 8 Final exam schedule is posted CSC263 exam Dec 11, 2-5pm This week s outline Graphs BFS Graph A

More information

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. An Introduction to Graph Theory

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. An Introduction to Graph Theory SCHOOL OF ENGINEERING & BUILT ENVIRONMENT Mathematics An Introduction to Graph Theory. Introduction. Definitions.. Vertices and Edges... The Handshaking Lemma.. Connected Graphs... Cut-Points and Bridges.

More information

CHAPTER 10 GRAPHS AND TREES. Copyright Cengage Learning. All rights reserved.

CHAPTER 10 GRAPHS AND TREES. Copyright Cengage Learning. All rights reserved. CHAPTER 10 GRAPHS AND TREES Copyright Cengage Learning. All rights reserved. SECTION 10.1 Graphs: Definitions and Basic Properties Copyright Cengage Learning. All rights reserved. Graphs: Definitions and

More information

Copyright 2000, Kevin Wayne 1

Copyright 2000, Kevin Wayne 1 Chapter 3 - Graphs Undirected Graphs Undirected graph. G = (V, E) V = nodes. E = edges between pairs of nodes. Captures pairwise relationship between objects. Graph size parameters: n = V, m = E. Directed

More information

csci 210: Data Structures Graph Traversals

csci 210: Data Structures Graph Traversals csci 210: Data Structures Graph Traversals Graph traversal (BFS and DFS) G can be undirected or directed We think about coloring each vertex WHITE before we start GRAY after we visit a vertex but before

More information

GRAPHS Lecture 17 CS2110 Spring 2014

GRAPHS Lecture 17 CS2110 Spring 2014 GRAPHS Lecture 17 CS2110 Spring 2014 These are not Graphs 2...not the kind we mean, anyway These are Graphs 3 K 5 K 3,3 = Applications of Graphs 4 Communication networks The internet is a huge graph Routing

More information

Prelim 2. CS 2110, November 20, 2014, 7:30 PM Extra Total Question True/False Short Answer

Prelim 2. CS 2110, November 20, 2014, 7:30 PM Extra Total Question True/False Short Answer Prelim 2 CS 2110, November 20, 2014, 7:30 PM 1 2 3 4 5 Extra Total Question True/False Short Answer Complexity Induction Trees Graphs Extra Credit Max 20 10 15 25 30 5 100 Score Grader The exam is closed

More information

3.1 Basic Definitions and Applications

3.1 Basic Definitions and Applications Graphs hapter hapter Graphs. Basic efinitions and Applications Graph. G = (V, ) n V = nodes. n = edges between pairs of nodes. n aptures pairwise relationship between objects: Undirected graph represents

More information

LECTURE NOTES OF ALGORITHMS: DESIGN TECHNIQUES AND ANALYSIS

LECTURE NOTES OF ALGORITHMS: DESIGN TECHNIQUES AND ANALYSIS Department of Computer Science University of Babylon LECTURE NOTES OF ALGORITHMS: DESIGN TECHNIQUES AND ANALYSIS By Faculty of Science for Women( SCIW), University of Babylon, Iraq Samaher@uobabylon.edu.iq

More information

Chapter 9 Graph Algorithms

Chapter 9 Graph Algorithms Chapter 9 Graph Algorithms 2 Introduction graph theory useful in practice represent many real-life problems can be slow if not careful with data structures 3 Definitions an undirected graph G = (V, E)

More information

11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions

11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions Introduction Chapter 9 Graph Algorithms graph theory useful in practice represent many real-life problems can be slow if not careful with data structures 2 Definitions an undirected graph G = (V, E) is

More information

Strongly connected: A directed graph is strongly connected if every pair of vertices are reachable from each other.

Strongly connected: A directed graph is strongly connected if every pair of vertices are reachable from each other. Directed Graph In a directed graph, each edge (u, v) has a direction u v. Thus (u, v) (v, u). Directed graph is useful to model many practical problems (such as one-way road in traffic network, and asymmetric

More information

Chapter 9 Graph Algorithms

Chapter 9 Graph Algorithms Introduction graph theory useful in practice represent many real-life problems can be if not careful with data structures Chapter 9 Graph s 2 Definitions Definitions an undirected graph is a finite set

More information

Lecture 5: Graphs. Rajat Mittal. IIT Kanpur

Lecture 5: Graphs. Rajat Mittal. IIT Kanpur Lecture : Graphs Rajat Mittal IIT Kanpur Combinatorial graphs provide a natural way to model connections between different objects. They are very useful in depicting communication networks, social networks

More information

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w Chapter 7 Trees 7.1 Introduction A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w Tree Terminology Parent Ancestor Child Descendant Siblings

More information

Solutions to Midterm 2 - Monday, July 11th, 2009

Solutions to Midterm 2 - Monday, July 11th, 2009 Solutions to Midterm - Monday, July 11th, 009 CPSC30, Summer009. Instructor: Dr. Lior Malka. (liorma@cs.ubc.ca) 1. Dynamic programming. Let A be a set of n integers A 1,..., A n such that 1 A i n for each

More information

Trees Algorhyme by Radia Perlman

Trees Algorhyme by Radia Perlman Algorhyme by Radia Perlman I think that I shall never see A graph more lovely than a tree. A tree whose crucial property Is loop-free connectivity. A tree which must be sure to span. So packets can reach

More information

Undirected Graphs. V = { 1, 2, 3, 4, 5, 6, 7, 8 } E = { 1-2, 1-3, 2-3, 2-4, 2-5, 3-5, 3-7, 3-8, 4-5, 5-6 } n = 8 m = 11

Undirected Graphs. V = { 1, 2, 3, 4, 5, 6, 7, 8 } E = { 1-2, 1-3, 2-3, 2-4, 2-5, 3-5, 3-7, 3-8, 4-5, 5-6 } n = 8 m = 11 Chapter 3 - Graphs Undirected Graphs Undirected graph. G = (V, E) V = nodes. E = edges between pairs of nodes. Captures pairwise relationship between objects. Graph size parameters: n = V, m = E. V = {

More information

Grades 7 & 8, Math Circles 31 October/1/2 November, Graph Theory

Grades 7 & 8, Math Circles 31 October/1/2 November, Graph Theory Faculty of Mathematics Waterloo, Ontario N2L 3G1 Centre for Education in Mathematics and Computing Grades 7 & 8, Math Circles 31 October/1/2 November, 2017 Graph Theory Introduction Graph Theory is the

More information

Graph Representation

Graph Representation Graph Representation Adjacency list representation of G = (V, E) An array of V lists, one for each vertex in V Each list Adj[u] contains all the vertices v such that there is an edge between u and v Adj[u]

More information

Lecture 26: Graphs: Traversal (Part 1)

Lecture 26: Graphs: Traversal (Part 1) CS8 Integrated Introduction to Computer Science Fisler, Nelson Lecture 6: Graphs: Traversal (Part ) 0:00 AM, Apr, 08 Contents Introduction. Definitions........................................... Representations.......................................

More information

CS6301 Programming and Data Structures II Unit -5 REPRESENTATION OF GRAPHS Graph and its representations Graph is a data structure that consists of following two components: 1. A finite set of vertices

More information