Java Programming: Program Design Including Data Structures Chapter 20: Graphs Java Programming: Program Design Including Data Structures
Chapter Objectives Learn about graphs Become familiar with the basic terminology of graph theory Discover how to represent graphs in computer memory Explore graphs as ADTs Java Programming: Program Design Including Data Structures
Chapter Objectives (continued) Examine and implement various graph traversal algorithms Learn how to implement the shortest path algorithm Examine and implement the minimal spanning tree algorithm Java Programming: Program Design Including Data Structures
Introduction Figure 20-1 Königsberg bridge problem Java Programming: Program Design Including Data Structures
Introduction (continued) The Königsberg bridge problem Starting at one land area, is it possible to walk across all the bridges exactly once and return to the starting land area? Can be represented as a graph Answer the question in the negative Java Programming: Program Design Including Data Structures
Introduction (continued) Figure 20-2 Graph representation of Königsberg bridge problem Java Programming: Program Design Including Data Structures
Graph Definitions and Notations If a is an element of X, then a X Y is a subset of X (Y X) If every element of Y is also an element of X Intersection of A and B (A B) Set of all the elements that are in A and B Union of A and B (A B) Set of all the elements that are in A or in B A X B = {(a, b) | a A, b B} Java Programming: Program Design Including Data Structures
Graph Definitions and Notations (continued) Graph G = (V,E) V is a finite nonempty set of vertices E V X V (called the set of edges) G is called a directed graph or digraph If elements of E(G) are ordered pairs Otherwise G is called an undirected graph If (u,v) is a digraph edge Vertex u is called the origin and vertex v the destination of the edge Java Programming: Program Design Including Data Structures
Graph Definitions and Notations (continued) Figure 20-3 Various undirected graphs Java Programming: Program Design Including Data Structures
Graph Definitions and Notations (continued) Figure 20-4 Various directed graphs Java Programming: Program Design Including Data Structures
Graph Definitions and Notations (continued) Adjacent vertices have an edge from one to the other Consequently, the edge is incident on both vertices Loop is an edge incident on a single vertex Parallel edges are incident on the same pair of vertices A simple graph has no loops and parallel edges Vertices are connected if they have a path Java Programming: Program Design Including Data Structures
Graph Definitions and Notations (continued) A connected graph has a path from any vertex to any other vertex Component of G Maximal subset of connected vertices G is strongly connected if any two vertices are connected If there is an edge from u to v u is adjacent to v v is adjacent from u Java Programming: Program Design Including Data Structures
Graph Representation Adjacency matrix Adjacency list Java Programming: Program Design Including Data Structures
Adjacency Matrix Two-dimensional n x n matrix (i, j)th entry is 1 if there is an edge from vi to vj Adjacency matrix of an undirected graph is symmetric Java Programming: Program Design Including Data Structures
Adjacency List Corresponding to each vertex v There is a linked list with all vertex u such that (u, v ) E(G) Because there are n nodes You can use an array A of size n A[ i ] contains the linked list of vertices to which vi is adjacent Java Programming: Program Design Including Data Structures
Adjacency List (continued) Figure 20-5 Adjacency list of graph G2 of Figure 20-4 Java Programming: Program Design Including Data Structures
Operations on Graphs Operations commonly performed on graphs Create the graph Clear the graph Determine whether the graph is empty Traverse the graph Print the graph Java Programming: Program Design Including Data Structures
Implementing Graph Operations Method isEmpty public boolean isEmpty() { return (gSize == 0); } Java Programming: Program Design Including Data Structures
Implementing Graph Operations (continued) Method createGraph public void createGraph() { Scanner console = new Scanner(System.in); String fileName; if (gSize != 0) clearGraph(); Scanner infile = null; try System.out.print(“Enter input file name: “); fileName = console.nextLine(); System.out.println(); infile = new Scanner(new FileReader(fileName)); } Java Programming: Program Design Including Data Structures
Implementing Graph Operations (continued) catch (FileNotFoundException fnfe) { System.out.println(fnfe.toString()); System.exit(0); } gSize = infile.nextInt(); //get the number of vertices for (int index = 0; index < gSize; index++) int vertex = infile.nextInt(); int adjacentVertex = infile.nextInt(); while (adjacentVertex != -999) graph[vertex].insertLast(adjacentVertex); adjacentVertex = infile.nextInt(); } //end while } // end for }//end createGraph Java Programming: Program Design Including Data Structures
Implementing Graph Operations (continued) Method clearGraph public void clearGraph() { int index; for (index = 0; index < gSize; index++) graph[index] = null; gSize = 0; } Java Programming: Program Design Including Data Structures
Implementing Graph Operations (continued) Method printGraph public void printGraph() { for (int index = 0; index < gSize; index++) System.out.print(index + “ ”); graph[index].print(); System.out.println(); } Java Programming: Program Design Including Data Structures
Implementing Graph Operations (continued) Constructor public Graph() { maxSize = 100; gSize = 0; graph = new UnorderedLinkedList[maxSize]; for (int i = 0; i < maxSize; i++) graph[i] = new UnorderedLinkedList<Integer>(); } Java Programming: Program Design Including Data Structures
Implementing Graph Operations (continued) Constructor public Graph(int size) { maxSize = size; gSize = 0; graph = new UnorderedLinkedList[maxSize]; for (int i = 0; i < maxSize; i++) graph[i] = new UnorderedLinkedList<Integer>(); } Java Programming: Program Design Including Data Structures
Graph Traversals Traversals Depth first traversal Similar to the preorder traversal of a binary tree Breadth first traversal Similar to traversing a binary tree level by level Java Programming: Program Design Including Data Structures
Depth First Traversal Method dft private void dft(int v, boolean[] visited) { visited[v] = true; System.out.print(“ ” + v + “ ”); //visit the vertex UnorderedLinkedList<Integer>. LinkedListIterator<Integer> graphIt = graph[v].iterator(); while (graphIt.hasNext()) int w = graphIt.next(); if (!visited[w]) dft(w, visited); } //end while } //end dft Java Programming: Program Design Including Data Structures
Depth First Traversal (continued) Method depthFirstTraversal public void depthFirstTraversal() { boolean[] visited; //array to keep track of the //visited vertices visited = new boolean[gSize]; for (int index = 0; index < gSize; index++) visited[index] = false; for (int index = 0; index < gSize; index++) //for each //vertex that if (!visited[index]) //has not been visited dft(index, visited); //do a depth first //traversal } //end depthFirstTraversal Java Programming: Program Design Including Data Structures
Depth First Traversal (continued) Method dftAtVertex public void dftAtVertex(int vertex) { boolean[] visited; visited = new boolean[gSize]; for (int index = 0; index < gSize; index++) visited[index] = false; dft(vertex,visited); } //end dftAtVertex Java Programming: Program Design Including Data Structures
Breadth First Traversal Method breadthFirstTraversal public void breadthFirstTraversal() { LinkedQueueClass<Integer> queue = new LinkedQueueClass<Integer>(); boolean[] visited; visited = new boolean[gSize]; for (int ind = 0; ind < gSize; ind++) visited[ind] = false; //initialize the array visited to false for (int index = 0; index < gSize; index++) if (!visited[index]) queue.addQueue(index); visited[index] = true; System.out.print(“ “ + index + “ “); while (!queue.isEmptyQueue()) Java Programming: Program Design Including Data Structures
Breadth First Traversal (continued) int u = queue.front(); queue.deleteQueue(); UnorderedLinkedList<Integer>. LinkedListIterator<Integer> graphIt = graph[u].iterator(); while (graphIt.hasNext()) { int w1 = graphIt.next(); if (!visited[w1]) queue.addQueue(w1); visited[w1] = true; System.out.print(“ “ + w1 + “ “); } } //end while } //end if } //end breadthFirstTraversal Java Programming: Program Design Including Data Structures
Shortest Path Algorithm Weight of the edge Nonnegative real number assigned to an edge Weighted graphs Graphs containing weighted edges Weight of the path Sum of the weights of all edges on path Shortest path Path with the smallest weight Java Programming: Program Design Including Data Structures
Shortest Path Algorithm (continued) Also called a greedy algorithm Developed by Dijkstra Let W be a two-dimensional n x n matrix, such that Java Programming: Program Design Including Data Structures
Shortest Path General algorithm: Initialize the array smallestWeight so that smallestWeight[u] = weights[vertex, u] Set smallestWeight[vertex] = 0 Find vertex v that is closest to vertex for which shortest path has not been determined Mark v as the (next) vertex for which smallest weight is found Update weight for each vertex w in G Java Programming: Program Design Including Data Structures
Shortest Path (continued) Figure 20-8 Weighted graph G Java Programming: Program Design Including Data Structures
Shortest Path (continued) Figure 20-9 Graph after Step 1 and 2 execute Java Programming: Program Design Including Data Structures
Shortest Path (continued) Figure 20-10 Graph after the first iteration of Steps 3, 4 and 5 Java Programming: Program Design Including Data Structures
Minimal Spanning Tree Weight of tree T, denoted by W(T) Spanning tree Sum of all weights of all edges in T Spanning tree Subgraph of G such that all vertices of G are in T Minimal spanning tree Spanning tree with the minimum weight Two well-known algorithms Prim’s algorithm Kruskal’s algorithm Java Programming: Program Design Including Data Structures
Minimal Spanning Tree (continued) Method minimalSpanning public void minimalSpanning(int sVertex) { source = sVertex; boolean[] mstv = new boolean[maxSize]; for (int j = 0; j < gSize; j++) mstv[j] = false; edges[j] = source; edgeWeights[j] = weights[source][j]; } mstv[source] = true; edgeWeights[source] = 0; Java Programming: Program Design Including Data Structures
Minimal Spanning Tree (continued) for (int i = 0; i < gSize - 1; i++) { double minWeight = Integer.MAX_VALUE; int startVertex = 0; int endVertex = 0; for (int j = 0; j < gSize; j++) if (mstv[j]) for (int k = 0; k < gSize; k++) if (!mstv[k] && weights[j][k] < minWeight) endVertex = k; startVertex = j; minWeight = weights[j][k]; } mstv[endVertex] = true; edges[endVertex] = startVertex; edgeWeights[endVertex] = minWeight; } //end for } //end minimalSpanning Java Programming: Program Design Including Data Structures
Some Well-Known Graph Theory Problems Three Utilities Problem Three houses are to be connected to three services by the means of underground pipelines Traveling Salesperson Problem Salesperson starts from home city and visit all cities exactly once and return home with the smallest cost Four Color Problem Color all vertices in a planer graph using only four colors Java Programming: Program Design Including Data Structures
Chapter Summary Graph theory Graph representation Graph traversals Vertices and edges Digraph Graph representation Adjacency matrix Adjacency list Graph traversals Depth first traversal Breadth first traversal Java Programming: Program Design Including Data Structures
Chapter Summary (continued) Shortest path algorithm Path with the smallest weight Minimal spanning tree Spanning tree with the minimum weight Algorithms: Prim and Kruskal Well-known problems Three Utilities Problem Traveling Salesperson Problem Four Color Problem Java Programming: Program Design Including Data Structures