Chapter 24 Graphs.

Slides:



Advertisements
Similar presentations
Lecture 15. Graph Algorithms
Advertisements

Weighted graphs Example Consider the following graph, where nodes represent cities, and edges show if there is a direct flight between each pair of cities.
Graphs CSC 220 Data Structure. Introduction One of the Most versatile data structures like trees. Terminology –Nodes in trees are vertices in graphs.
Part A - Terminology and Traversals
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
Graphs Chapter Chapter Contents Some Examples and Terminology Road Maps Airline Routes Mazes Course Prerequisites Trees Traversals Breadth-First.
Graphs Chapter 12. Chapter Objectives  To become familiar with graph terminology and the different types of graphs  To study a Graph ADT and different.
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Chapter 8, Part I Graph Algorithms.
Graphs Chapter 30 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
© 2006 Pearson Addison-Wesley. All rights reserved14 A-1 Chapter 14 excerpts Graphs (breadth-first-search)
Data Structures Using C++
Graphs Graphs are the most general data structures we will study in this course. A graph is a more general version of connected nodes than the tree. Both.
Data Structure and Algorithms (BCS 1223) GRAPH. Introduction of Graph A graph G consists of two things: 1.A set V of elements called nodes(or points or.
CS 206 Introduction to Computer Science II 11 / 11 / Veterans Day Instructor: Michael Eckmann.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 21: Graphs.
ITEC200 – Week 12 Graphs. 2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study.
Graphs Chapter 30 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Graphs Chapter 12. Chapter 12: Graphs2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study a Graph.
Spring 2010CS 2251 Graphs Chapter 10. Spring 2010CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs.
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 03 / 25 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 11 / 09 / 2009 Instructor: Michael Eckmann.
Fall 2007CS 2251 Graphs Chapter 12. Fall 2007CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs To.
CS 206 Introduction to Computer Science II 03 / 30 / 2009 Instructor: Michael Eckmann.
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
Graphs Chapter 28 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 13: Graphs Java Software Structures: Designing and Using Data.
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
1 Chapter 9 Graph Algorithms Real-life graph problems Algorithms for some graph problems Choice of data structures for graph problems.
© 2006 Pearson Addison-Wesley. All rights reserved14 A-1 Chapter 14 Graphs.
Chapter 14 Graphs. © 2004 Pearson Addison-Wesley. All rights reserved Terminology G = {V, E} A graph G consists of two sets –A set V of vertices,
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Common final examinations When: Wednesday, 12/11, 3:30-5:30 PM Where: Ritter Hall - Walk Auditorium 131 CIS 1166 final When: Wednesday, 12/11, 5:45-7:45.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Graphs. Definitions A graph is two sets. A graph is two sets. –A set of nodes or vertices V –A set of edges E Edges connect nodes. Edges connect nodes.
Graphs. Graphs Similar to the graphs you’ve known since the 5 th grade: line graphs, bar graphs, etc., but more general. Those mathematical graphs are.
Graphs Chapter Chapter Contents Some Examples and Terminology Road Maps Airline Routes Mazes Course Prerequisites Trees Traversals Breadth-First.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
1 Directed Graphs Chapter 8. 2 Objectives You will be able to: Say what a directed graph is. Describe two ways to represent a directed graph: Adjacency.
COSC 2007 Data Structures II
Graphs Chapter 12. Chapter 12: Graphs2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study a Graph.
© 2006 Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs.
Graphs Upon completion you will be able to:
Graphs and Paths : Chapter 15 Saurav Karmakar
Chapter 20: Graphs. Objectives In this chapter, you will: – Learn about graphs – Become familiar with the basic terminology of graph theory – Discover.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 7: Graphs Data Structures.
Data Structures and Algorithm Analysis Graph Algorithms Lecturer: Jing Liu Homepage:
Lecture #13. Topics 1.The Graph Abstract Data Type. 2.Graph Representations. 3.Elementary Graph Operations.
1 GRAPHS – Definitions A graph G = (V, E) consists of –a set of vertices, V, and –a set of edges, E, where each edge is a pair (v,w) s.t. v,w  V Vertices.
Graphs. What is a graph? In simple words, A graph is a set of vertices and edges which connect them. A node (or vertex) is a discrete position in the.
Graphs Chapter 15 introduces graphs which are probably the most general and commonly-used data structure. This lecture introduces heaps, which are used.
CS212: Data Structures and Algorithms
Unit 10 Graphs (1) King Fahd University of Petroleum & Minerals
Chapter 13: The Graph Abstract Data Type
I206: Lecture 15: Graphs Marti Hearst Spring 2012.
Data Structures and Algorithms for Information Processing
Graphs Chapter 13.
Java Software Structures: John Lewis & Joseph Chase
Graphs Chapter 11 Objectives Upon completion you will be able to:
Graphs.
Chapter 11 Graphs.
Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Chapter 10 The Graph ADT.
Chapter 14 Graphs © 2011 Pearson Addison-Wesley. All rights reserved.
INTRODUCTION A graph G=(V,E) consists of a finite non empty set of vertices V , and a finite set of edges E which connect pairs of vertices .
Presentation transcript:

Chapter 24 Graphs

Chapter Scope Directed and undirected graphs Weighted graphs (networks) Common graph algorithms Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Graphs Like trees, graphs are made up of nodes and the connections between those nodes In graph terminology, we refer to the nodes as vertices and refer to the connections among them as edges Vertices are typically referenced by a name or label Edges are referenced by a pairing of the vertices (A, B) that they connect An undirected graph is a graph where the pairings representing the edges are unordered Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Undirected Graphs An undirected graph: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Undirected Graphs An edge in an undirected graph can be traversed in either direction Two vertices are said to be adjacent if there is an edge connecting them Adjacent vertices are sometimes referred to as neighbors An edge of a graph that connects a vertex to itself is called a self-loop or sling An undirected graph is considered complete if it has the maximum number of edges connecting vertices Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Undirected Graphs A path is a sequence of edges that connects two vertices in a graph The length of a path in is the number of edges in the path (or the number of vertices minus 1) An undirected graph is considered connected if for any two vertices in the graph there is a path between them Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Undirected Graphs An example of an undirected graph that is not connected: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Cycles A cycle is a path in which the first and last vertices are the same and none of the edges are repeated A graph that has no cycles is called acyclic Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Directed Graphs A directed graph, sometimes referred to as a digraph, is a graph where the edges are ordered pairs of vertices This means that the edges (A, B) and (B, A) are separate, directional edges in a directed graph Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Directed Graphs A directed graph with vertices A, B, C, D edges (A, B), (A, D), (B, C), (B, D) and (D, C) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Directed Graphs Previous definitions change slightly for directed graphs a path in a direct graph is a sequence of directed edges that connects two vertices in a graph a directed graph is connected if for any two vertices in the graph there is a path between them if a directed graph has no cycles, it is possible to arrange the vertices such that vertex A precedes vertex B if an edge exists from A to B Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Directed Graphs A connected directed graph and an unconnected directed graph: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Weighted Graphs A weighted graph, sometimes called a network, is a graph with weights (or costs) associated with each edge The weight of a path in a weighted graph is the sum of the weights of the edges in the path Weighted graphs may be either undirected or directed For weighted graphs, we represent each edge with a triple including the starting vertex, ending vertex, and the weight (Boston, New York, 120) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Weighted Graphs We could use an undirected network to represent flights between cities The weights are the cost Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Weighted Graphs A directed version of the graph could show different costs depending on the direction Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Common Graph Algorithms There are a number of a common algorithms that may apply to undirected, directed, and/or weighted graphs These include various traversal algorithms algorithms for finding the shortest path algorithms for finding the least costly path in a network algorithms for answering simple questions (such as connectivity) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Graph Traversals There are two main types of graph traversal algorithms breadth-first: behaves much like a level-order traversal of a tree depth-first: behaves much like the preorder traversal of a tree One difference: there is no root node present in a graph Graph traversals may start at any vertex in the graph Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Breadth-First Traversal We can construct a breadth-first traversal for a graph using a queue and an iterator We will use the queue to manage the traversal and the iterator to build the result Breadth-first traversal algorithm overview enqueue the starting vertex, and mark it as “visited” loop until queue is empty dequeue first vertex and add it to iterator enqueue each unmarked vertex adjacent to the dequeued vertex mark each vertex enqueued as “visited” Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/. Returns an iterator that performs a breadth first /** * Returns an iterator that performs a breadth first * traversal starting at the given index. * * @param startIndex the index from which to begin the traversal * @return an iterator that performs a breadth first traversal */ public Iterator<T> iteratorBFS(int startIndex) { Integer x; QueueADT<Integer> traversalQueue = new LinkedQueue<Integer>(); UnorderedListADT<T> resultList = new ArrayUnorderedList<T>(); if (!indexIsValid(startIndex)) return resultList.iterator(); boolean[] visited = new boolean[numVertices]; for (int i = 0; i < numVertices; i++) visited[i] = false; traversalQueue.enqueue(new Integer(startIndex)); visited[startIndex] = true; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

while (. traversalQueue. isEmpty()) { x = traversalQueue while (!traversalQueue.isEmpty()) { x = traversalQueue.dequeue(); resultList.addToRear(vertices[x.intValue()]); // Find all vertices adjacent to x that have not been visited // and queue them up for (int i = 0; i < numVertices; i++) if (adjMatrix[x.intValue()][i] && !visited[i]) traversalQueue.enqueue(new Integer(i)); visited[i] = true; } return new GraphIterator(resultList.iterator()); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Graph Traversals A traversal example: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Depth-First Traversal Use nearly the same approach as the breadth-first traversal, but replace the queue with a stack Additionally, do not mark a vertex as visited until it has been added to the iterator Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/. Returns an iterator that performs a depth first traversal /** * Returns an iterator that performs a depth first traversal * starting at the given index. * * @param startIndex the index from which to begin the traversal * @return an iterator that performs a depth first traversal */ public Iterator<T> iteratorDFS(int startIndex) { Integer x; boolean found; StackADT<Integer> traversalStack = new LinkedStack<Integer>(); UnorderedListADT<T> resultList = new ArrayUnorderedList<T>(); boolean[] visited = new boolean[numVertices]; if (!indexIsValid(startIndex)) return resultList.iterator(); for (int i = 0; i < numVertices; i++) visited[i] = false; traversalStack.push(new Integer(startIndex)); resultList.addToRear(vertices[startIndex]); visited[startIndex] = true; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

while (. traversalStack. isEmpty()) { x = traversalStack while (!traversalStack.isEmpty()) { x = traversalStack.peek(); found = false; // Find a vertex adjacent to x that has not been visited // and push it on the stack for (int i = 0; (i < numVertices) && !found; i++) if (adjMatrix[x.intValue()][i] && !visited[i]) traversalStack.push(new Integer(i)); resultList.addToRear(vertices[i]); visited[i] = true; found = true; } if (!found && !traversalStack.isEmpty()) traversalStack.pop(); return new GraphIterator(resultList.iterator()); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Connectivity A graph is connected if and only if for each vertex v in a graph containing n vertices, the size of the result of a breadth-first traversal at v is n Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Spanning Trees A spanning tree is a tree that includes all of the vertices of a graph and some, but possibly not all, of the edges Since trees are also graphs, for some graphs, the graph itself will be a spanning tree, and thus the only spanning tree Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Spanning Tree An example of a spanning tree: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Minimum Spanning Tree A minimum spanning tree (MST) is a spanning tree where the sum of the weights of the edges is less than or equal to the sum of the weights for any other spanning tree for the same graph Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Minimum Spanning Tree Minimal Spanning Tree algorithm overview pick an arbitrary starting vertex and add it to our MST add all of the edges that include our starting vertex to a minheap ordered by weight remove the minimum edge from the minheap and add the edge and the new vertex to our MST add to the minheap all of the edges that include this new vertex and whose other vertex is not already in the MST continue until the minheap is empty or all vertices are in the MST Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Shortest Path There are two possibilities for determining the “shortest” path in a graph determine the literal shortest path between a starting vertex and a target vertex (the least number of edges between the two vertices) simplest approach – a variation of the breadth-first traversal algorithm look for the cheapest path in a weighted graph use a minheap or a priority queue storing vertex, weight pairs Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing Graphs Strategies for implementing graphs: Adjacency lists use a set of graph nodes which contain a linked list storing the edges within each node for weighted graphs, each edge would be stored as a triple including the weight Adjacency matrices use a two dimensional array each position of the array represents an intersection between two vertices in the graph each intersection is represented by a boolean value indicating whether or not the two vertices are connected Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Adjacency Matrices An undirected graph and it's adjacency matrix: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Adjacency Matrices A directed graph and its adjacency matrix: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; import java. util. Iterator; / package jsjf; import java.util.Iterator; /** * GraphADT defines the interface to a graph data structure. * * @author Java Foundations * @version 4.0 */ public interface GraphADT<T> { * Adds a vertex to this graph, associating object with vertex. * @param vertex the vertex to be added to this graph public void addVertex(T vertex); * Removes a single vertex with the given value from this graph. * @param vertex the vertex to be removed from this graph public void removeVertex(T vertex); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/. Inserts an edge between two vertices of this graph /** * Inserts an edge between two vertices of this graph. * * @param vertex1 the first vertex * @param vertex2 the second vertex */ public void addEdge(T vertex1, T vertex2); * Removes an edge between two vertices of this graph. public void removeEdge(T vertex1, T vertex2); * Returns a breadth first iterator starting with the given vertex. * @param startVertex the starting vertex * @return a breadth first iterator beginning at the given vertex public Iterator iteratorBFS(T startVertex); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/. Returns a depth first iterator starting with the given vertex /** * Returns a depth first iterator starting with the given vertex. * * @param startVertex the starting vertex * @return a depth first iterator starting at the given vertex */ public Iterator iteratorDFS(T startVertex); * Returns an iterator that contains the shortest path between * the two vertices. * @param targetVertex the ending vertex * @return an iterator that contains the shortest path * between the two vertices public Iterator iteratorShortestPath(T startVertex, T targetVertex); * Returns true if this graph is empty, false otherwise. * @return true if this graph is empty public boolean isEmpty(); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/. Returns true if this graph is connected, false otherwise /** * Returns true if this graph is connected, false otherwise. * * @return true if this graph is connected */ public boolean isConnected(); * Returns the number of vertices in this graph. * @return the integer number of vertices in this graph public int size(); * Returns a string representation of the adjacency matrix. * @return a string representation of the adjacency matrix public String toString(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase package jsjf; import java.util.Iterator; /** * NetworkADT defines the interface to a network. * * @author Java Foundations * @version 4.0 */ public interface NetworkADT<T> extends GraphADT<T> { * Inserts an edge between two vertices of this graph. * @param vertex1 the first vertex * @param vertex2 the second vertex * @param weight the weight public void addEdge(T vertex1, T vertex2, double weight); * Returns the weight of the shortest path in this network. * @return the weight of the shortest path in this network public double shortestPathWeight(T vertex1, T vertex2); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase package jsjf; import jsjf.exceptions.*; import java.util.*; /** * Graph represents an adjacency matrix implementation of a graph. * * @author Java Foundations * @version 4.0 */ public class Graph<T> implements GraphADT<T> { protected final int DEFAULT_CAPACITY = 5; protected int numVertices; // number of vertices in the graph protected boolean[][] adjMatrix; // adjacency matrix protected T[] vertices; // values of vertices protected int modCount; * Creates an empty graph. public Graph() numVertices = 0; this.adjMatrix = new boolean[DEFAULT_CAPACITY][DEFAULT_CAPACITY]; this.vertices = (T[])(new Object[DEFAULT_CAPACITY]); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/. Inserts an edge between two vertices of the graph /** * Inserts an edge between two vertices of the graph. * * @param vertex1 the first vertex * @param vertex2 the second vertex */ public void addEdge(T vertex1, T vertex2) { addEdge(getIndex(vertex1), getIndex(vertex2)); } * @param index1 the first index * @param index2 the second index public void addEdge(int index1, int index2) if (indexIsValid(index1) && indexIsValid(index2)) adjMatrix[index1][index2] = true; adjMatrix[index2][index1] = true; modCount++; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/. Adds a vertex to the graph, expanding the capacity of the graph /** * Adds a vertex to the graph, expanding the capacity of the graph * if necessary. It also associates an object with the vertex. * * @param vertex the vertex to add to the graph */ public void addVertex(T vertex) { if ((numVertices + 1) == adjMatrix.length) expandCapacity(); vertices[numVertices] = vertex; for (int i = 0; i < numVertices; i++) adjMatrix[numVertices][i] = false; adjMatrix[i][numVertices] = false; } numVertices++; modCount++; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/. Creates new arrays to store the contents of the graph with /** * Creates new arrays to store the contents of the graph with * twice the capacity. */ protected void expandCapacity() { T[] largerVertices = (T[])(new Object[vertices.length*2]); boolean[][] largerAdjMatrix = new boolean[vertices.length*2][vertices.length*2]; for (int i = 0; i < numVertices; i++) for (int j = 0; j < numVertices; j++) largerAdjMatrix[i][j] = adjMatrix[i][j]; } largerVertices[i] = vertices[i]; vertices = largerVertices; adjMatrix = largerAdjMatrix; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase