Download Presentation
## Chapter 27 Graph Applications

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -

**Objectives (1)**• To give applications of graphs and explain the Seven Bridges of Königsberg problem (§27.1) • To describe the graph terminologies: vertices, edges, simple graphs, weighted/unweighted graphs, and directed/undirected graphs (§27.2) • To represent vertices and edges using lists, adjacent matrices, and adjacent lists (§27.3) • To model graphs using the Graph interface, the AbstractGraph class, and the UnweightedGraph class (§27.4)**Objectives (2)**• To represent the traversal of a graph using the AbstractGraph.Tree class (§27.5) • To design and implement depth-first search (§27.6) • To design and implement breadth-first search (§27.7) • To solve the nine tail problem using breadth-first search (§27.8)**Modeling Using Graphs**• The problem of finding the shortest distance between two cities can be modeled using a graph where one measures the distance between two vertices (cities)**Seven Bridges of Königsberg (1)**• The city of Königsberg, Prussia was divided by the Pregel river • There were two islands on the river • The city and island were connected by seven bridges • Problem • How can one take a walk, cross each bridge exactly once, and return to the starting point?**Seven Bridges of Königsberg (2)**Each land mass was represented by a dot (vertex or node) and each bridge was represented by a line (edge)**Seven Bridges of Königsberg (3)**• Is there a path from any vertex, traversing all the edges exactly once and returning to the starting vertex? • No • Euler proved that for such a path to exist, each vertex must have an even number of edges**A vertex represents an airport and stores the three-letter**airport code An edge represents a flight route between two airports and stores the mileage of the route Graph Example 849 PVD 1843 ORD 142 SFO 802 LGA 1743 337 1387 HNL 2555 1099 1233 LAX 1120 DFW MIA**cs.saddleback.edu**saddleback.edu att.net cox.net Delores Sam Jane Other Applications • Electronic circuits • Printed circuit board • Integrated circuit • Transportation networks • Highway network • Flight network • Computer networks • Local area network • Internet • Web • Databases • Entity-relationship diagram cslab1C cslab1D math.saddleback.edu qwest.net**Basic Graph Terminology**• Graph Theory – the study of graphs • Graph– A mathematical structure that represents relationships among entities in the real world • It consists of a non-empty set of vertices, nodes or points and a set of edges that connect the vertices • It is defined as G = (V,E) where V represents the set of vertices and E represents the set of edge • For example V = {“Seattle”, “San Francisco”, “Los Angeles”, …) and E = {{ “Seattle”,” San Francisco”}, {{ “Seattle”,” Chicago”}, {{ “Seattle”,” Denver”}, …}**Directed edge**ordered pair of vertices (u,v) first vertex u is the origin second vertex v is the destination e.g., a flight Directed graph all the edges are directed e.g., route network Edge Types (1) flight AA 1206 ORD PVD ORD PVD ATL**Undirected edge**unordered pair of vertices (u,v) Move both direction between vertices e.g., a flight route Undirected graph all the edges are undirected e.g., flight network Edge Types (2) 849 miles ORD PVD ORD PVD ATL**Weighted Graphs**• In a weightedgraph, each edge has an associated numerical value, called the weight of the edge • Edge weights may represent distances, costs, etc. • Example: • In a flight route graph, the weight of an edge represents the distance in miles between the endpoint airports 849 PVD 1843 ORD 142 SFO 802 LGA 1205 1743 337 1387 HNL 2555 1099 1233 LAX 1120 DFW MIA**Adjacent Vertices and Edges**• Vertices U and V areadjacent if there is an edge whose end vertices are U and V • Edges a and b areadjacent if they are connected to the same vertex • Two vertices are called neighborsif they are adjacent • Two edges are called neighbors if they are adjacent V a b U d X c e W g f Y**Incident Edges, Degree, and Loops**• An edge that joins two vertices is said to be incident to both vertices • a is incident to both U and V • Degreeof a vertex V, deg(V) • Number of incident edges of V • X has degree 5 • Loop • Edge that connects a vertex to itself • j is a loop V a b h j Z U d X c e i W g f Y**Parallel Edges and Simple Graphs**• Collection • Group of edges • Parallel edges • Two undirected edges that have the same end vertices • Two directed edges that have the same origin and destination • h and i are parallel edges • A graph is simple if it does not have parallel edges or loops V h a b Z U d X j c e i W g f Y**Subgraphs**• A subgraph S of a graph G is a graph such that • The vertices of S are a subset of the vertices of G • The edges of S are a subset of the edges of G • A spanning subgraphof G is a subgraph that contains all the vertices of G Subgraph Spanning subgraph**Representing Graphs**• Representing Vertices • Representing Edges • Edge Array • Edge Objects • Adjacency Matrices • Adjacency Lists**Representing Vertices**• Vertices can be stored in an array • For example • String [ ] vertices = {“Seattle”, “Denver”, “Boston”} • vertices [0] = Seattle; • vertices [1] = Denver; • vertices [2] = Boston; • Vertices can be referenced by its name or index • Vertices can be objects of any type**Representing Edges: Edge Array**• Edges can be stored in a two dimensional array • For example • int [ ] edges ={ {0,1}, {0,3}, {0,5}} • where i and j are the indices of the vertices**Representing Edges: Edge Objects (1)**• Another way to represent edges is to define edges as objects and then store the edges in an array using java.util.ArrayList public class Edge { int u; int v; public Edge (int u, int v) { this.u=u; this.v = v; } }**Representing Edges: Edge Objects (2)**• One can then store all the edges using the following: java.util.ArrayList<Edge> list = new java.util.ArrayList<Edge> (); list.add(new Edge (0,1)); list.add(new Edge (0,3)); list.add(new Edge (0,5)); … Representing edges in an array is intuitive but not efficient**Representing Edges: Adjacency Matrices (1)**• Another way to represent edges • Assume that a graph has n vertices, one can use a two-dimensional n x n array (adjacencyMatrix) to represent the edges where each element in the array is either a0or a1 • adjacencyMatrix[i][j] is1if there is a an edge from vertex ito vertex j other it is 0**Representing Edges: Adjacency Matrices (2)**• If the graph is undirected, the matrix will be symmetrical because adjacencyMatrix[i][j] is the same as adjacencyMatrix[j][i] • See adjacency matrix in section 27.3.5 • int [ ] adjacencyMatrix ={ {0,1,0,1,0,1,0,0,0,0,0,0}, // Seattle • Since there are edges between Seattle and San Francisco, Denver, and Chicago**Representing Edges: Adjacency Lists (1)**• Another way to represent edges • To represent edges using an Adjacency list, one defines an array of linked lists (section 27.3.5) • The array has n entries where each entry represents a vertex • The linked list for vertex i contains all the vertices j such that there is an edge from vertex ito vertex j**Representing Edges: Adjacency Lists (2)**• To represent the edges in Figure 27.1 one uses java.util.LinkedList [ ] neighbors = new java.util.LinkedList(12); • list[0] contains all the vertices adjacent to vertex 0 (Seattle) • See Figure 27.5**Adjacency Matrices vs. Adjacency Lists**• If the graph is dense (lots of edges), adjacency matrix are more efficient • If the graph is sparse (few edges), adjacency lists are more efficient • It takes O(1) time to check whether two vertices are connected using a adjacency matrix • It takes O(n) time to print all the edges using a adjacency list where n is the number of edges**Modeling Graphs**• One can define an interface called Graphthat contains all the common operations for graphs • Lets define an abstract class called AbstractGraphthat partially implements the Graph interface • Concrete class will be added to the design • Unweighted Graph • Weighted Graph Similar framework as the Java Collections framework**Common Graph Operations**• Obtain the number of vertices • Obtain all the vertices • Obtain the vertex object with a specified index • Obtain the index of a vertex with a specified name • Obtain the neighbors of a vertex • Obtain the adjacency matrix • Obtain the degree of a vertex • Perform a depth-first search • Perform a breadth-first search**Graph**related classes**AbstractGraph Class Data Fields**• The AbstractGraphclass defines the following data fields • vertices • Used to store the vertices • neighbors • Used to store the edges in the adjacency lists • neighbors[i] stores all the vertices adjacent to vertex i**AbstractGraph Class Methods**• Four overloaded constructors are used to create graphs from arrays or lists of edges and vertices • The createAdjacencyLists ( )method creates adjacency lists from edges in an array or list depending on its parameters • The getAdjacencyMatrix ( ) method returns a two-dimensional array representing an adjacency matrix of edges**Source Code for the Graph Related Classes**Graph AbstractGraph UnweightedGraph TestGraph Listings 27.2 – 27.4**Graph Traversals**• Systematic procedure for exploring a graph by examining all of its vertices and edges • Process of visiting each vertex in the graph exactly once**Graph Traversals Methods**• Two common methods • Depth-first traversal (depth-first search) • Breadth-first traversal (breadth-first search) • Both traversals result in a spanning tree • A spanning tree of a graph is a subgraph that is a tree and connects all the vertices in the graph**AbstractGraph.Tree**• Tree is an inner class defined within the AbstractGraphclass (see page 872) • AbstractGraph.Treeisdifferent from the Treeinterface which was defined in a section 27.5.2 • AbstractGraph.Treedescribes a search order of the nodes in a graph**AbstractGraph.Tree**Tree is inner class of AbstractGraph**AbstractGraph.Tree Class Methods (1)**• TheTreeclass methods • Getroot () method – returns the root of a tree • getSearchOrders () method – obtains the order of the vertices • getParent (v)method – finds the parent of vertex v • getNumberOfVerticesFound () method – returns the number of vertices searched**AbstractGraph.Tree Class Methods (2)**• printPath (v) method – displays a path from the root to v • printTree () method – displays all the edges in the tree • pathIterator (int v) method – returns an iterator for a path from the root to the vertex v • The iterator is an instance of the PathIteratorclass which implements java.util.Iterator • The PathIteratorclass must implement the hasNext(), next(), and remove() methods**Cycle**Circular sequence of alternating vertices and edges Each edge is preceded and followed by vertices Simple cycle Cycle such that all its vertices and edges are distinct Examples C1=(V,b,X,g,Y,f,W,c,U,a) is a simple cycle C2=(U,c,W,e,X,g,Y,f,W,d,V,a) is a cycle that is not simple Directed cycle All edges are directed Traversed along their direction Cycles V a b d U X Z h c e C1 W g f C2 Y**Depth-First Search**• Depth-first search (DFS) is a general technique for traversing a graph • A DFS traversal of a graph G • Visits all the vertices G • Determines whether G is connected**Depth-First Search**• The DFS of a graph is like the depth-first search of a tree discussed in section 27.2.4 • In the case of a tree, the search starts from the root • In a graph, the search can start from any vertex • The DFS of a graph first visits a vertex then recursively visits all the vertices adjacent to that vertex • Graph may contains cycles that lead to an infinite recursion • One needs to keep track of the vertices that have been visited**Depth-First Search Algorithm (1)**• The search starts from some vertex v • After visiting v, the next vertex to be visited is 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 (2)**dfs(vertex v) { visit v; for each neighbor w of v if (w has not been visited) { dfs(w); } } • One uses an array called isVisitedto denote whether a vertex has been visited**Depth-First Search Example**• First visit 0, then visit its neighbor 1**Depth-First Search Example**• 1 has three neighbors (0, 2, and 4) • 0 has already been visited, so lets visit 2**Depth-First Search Example**• 2 has three neighbors (0, 1, and 3) • 0and1 have already been visited, so lets visit 3 • Order is 0, 1, 2, 3**Depth-First Search Example**• Since all the neighbors of 3 have been visited, backtrack to 2and then 1 • 0and2 have already been visited, so lets visit 4 • Backtrack to 1and then to 0 • The search is search ends**Another Depth-First Search Example**• Search order (assuming that the left edges are chosen before right edges) • A, B, D, F, E, C, G**Depth-First Search Order**DFS Order (1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)