Graphs and Digraphs Chapter 14.

Slides:



Advertisements
Similar presentations
CSE 373 Graphs 1: Concepts, Depth/Breadth-First Search
Advertisements

CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
CSE 373: Data Structures and Algorithms Lecture 19: Graphs III 1.
Graphs Chapter Chapter Contents Some Examples and Terminology Road Maps Airline Routes Mazes Course Prerequisites Trees Traversals Breadth-First.
Graphs. 2 Some Examples and Terminology A graph is a set of vertices (nodes) and a set of edges (arcs) such that each edge is associated with exactly.
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.
Graph Search Methods Spring 2007 CSE, POSTECH. Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u. A search method.
© 2006 Pearson Addison-Wesley. All rights reserved14 A-1 Chapter 14 excerpts Graphs (breadth-first-search)
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.
Graphs CS3240, L. grewe.
Graphs.
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.
Graph & BFS.
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 CS-240/341. Uses for Graphs computer networks and routing airline flights geographic maps course prerequisite structures tasks for completing a.
Graphs.
Graph COMP171 Fall Graph / Slide 2 Graphs * Extremely useful tool in modeling problems * Consist of: n Vertices n Edges D E A C F B Vertex Edge.
Graphs. Graph definitions There are two kinds of graphs: directed graphs (sometimes called digraphs) and undirected graphs Birmingham Rugby London Cambridge.
Introduction to Graphs
Graph & BFS Lecture 22 COMP171 Fall Graph & BFS / Slide 2 Graphs * Extremely useful tool in modeling problems * Consist of: n Vertices n Edges D.
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 / 03 / 2008 Instructor: Michael Eckmann.
Graphs. Graphs Many interesting situations can be modeled by a graph. Many interesting situations can be modeled by a graph. Ex. Mass transportation system,
CS 206 Introduction to Computer Science II 11 / 05 / 2008 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.
Graphs & Graph Algorithms Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
Computer Science 112 Fundamentals of Programming II Introduction to Graphs.
Chapter 2 Graph Algorithms.
© 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.
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.
10 Copyright © William C. Cheng Data Structures - CSCI 102 Graph Terminology A graph consists of a set of Vertices and a set of Edges C A B D a c b d e.
Data Structures CSCI 132, Spring 2014 Lecture 38 Graphs
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.
Graphs A graphs is an abstract representation of a set of objects, called vertices or nodes, where some pairs of the objects are connected by links, called.
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.
Graphs Slide credits:  K. Wayne, Princeton U.  C. E. Leiserson and E. Demaine, MIT  K. Birman, Cornell U.
© 2006 Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs.
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.
Chapter 05 Introduction to Graph And Search Algorithms.
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.
Csc 2720 Instructor: Zhuojun Duan
Graphs Representation, BFS, DFS
Graphs Chapter 13.
Graphs Chapter 11 Objectives Upon completion you will be able to:
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Graphs.
Chapter 14 Graphs © 2011 Pearson Addison-Wesley. All rights reserved.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Presentation transcript:

Graphs and Digraphs Chapter 14

Graphs General graphs differ from trees need not have a root node no implicit parent-child relationship may be several (or no) paths from one vertex to another Directed graphs useful in modeling: communication networks flow from one node to another Graphs may be directed or undirected

Directed Graphs Also called digraphs A finite set of elements (vertices or nodes) A finite set of direct arcs or edges Edges connect pairs of vertices Edges 1 2 3 5 4 Vertices

Graph Functionality Basic Operations Construct a graph Check if empty Destroy a directed graph Insert a new node Insert directed edge between nodes or from a node to itself Delete a node and all directed edges to or from it

Graph Functionality Basic Operations ctd. Delete directed edge between two existing nodes Search for a value in a node, starting from a given node Traversal Determining if node x is reachable from node y Determining the number of paths from x to y Determine shortest path from x to y

Graph Representation Adjacency matrix representation for directed graph with vertices numbered 1, 2, … n Defined as n by n matrix named adj The [i,j] entry set to 1 (true) if vertex j is adjacent to vertex i (there is a directed arc from i to j) 0 (false) otherwise

Graph Representation The adjacency matrix for the digraph at the right is 1 2 3 5 4 columns j 1 2 3 4 5 Entry [ 1, 5 ] set to true Edge from vertex 1 to vertex 5 rows i

Graph Representation Weighted digraph A complete graph There exists a "cost" or "weight" associated with each arc Then that cost is entered in the adjacency matrix A complete graph has an edge between each pair of vertices N nodes will mean N * (N – 1) edges

Weights A weighted graph.

Adjacency Matrix Out-degree of ith vertex (node) Sum of 1's (true's) in row i In-degree of jth vertex (node) Sum of the 1's (true's) in column j What is the out-degree of node 4? _____ What is the in-degree of node 3? _____

This is the number of paths of length 2 from node 1 to node 3 Adjacency Matrix Consider the sum of the products of the pairs of elements from row i and column j Fill in the rest of adj 2 1 adj 2 adj 1 2 3 4 5 1 2 3 4 5 1 This is the number of paths of length 2 from node 1 to node 3

Adjacency Matrix Basically we are doing matrix multiplication What is adj 3? The value in each entry would represent The number of paths of length 3 From node i to node j Consider the meaning of the generalization of adj n

Adjacency-List Representation What happens to the adjacency matrix when there are few edges? Implications This is a waste of space Better to use an array of pointers to linked row-lists This is called an Adjacency-list representation The matrix is sparse.

The collection of nodes with accompanying edges Adjacency List The node The collection of nodes with accompanying edges The edges

Searching a Graph Recall that with a tree we search from the root But with a digraph … may not be a vertex from which every other vertex can be reached may not be possible to traverse entire digraph (regardless of starting vertex)

Searching a Graph We must determine which nodes are reachable from a given node Two standard methods of searching: Depth first search Breadth first search

Trees The visitation order of two traversals; (a) depth first; (b) breadth first.

Depth-First Search Start from a given vertex v Visit first neighbor w, of v Then visit first neighbor of w which has not already been visited etc. … Continues until all nodes of graph have been examined If dead-end reached backup to last visited node examine remaining neighbors

Depth-First Traversal Visits a vertex, then A neighbor of the vertex, A neighbor of the neighbor, Etc. Advance as possible from the original vertex Then back up by one vertex Considers the next neighbor

Depth-First Search Algorithm getDepthFirstTraversal(originVertex) vertexStack = a new stack to hold vertices as they are visited traversalOrder = a new queue for the resulting traversal order Mark originVertex as visited traversalOrder.enqueue(originVertex) vertexStack.push(originVertex) while (!vertexStack.isEmpty()) { topVertex = vertexStack.peek() if (topVertex has an unvisited neighbor) { nextNeighbor = next unvisited neighbor of topVertex Mark nextNeighbor as visited traversalOrder.enqueue(nextNeighbor) vertexStack.push(nextNeighbor) } else // all neighbors are visited vertexStack.pop() return traversalOrder

Depth-First Traversal A trace of a depth-first traversal beginning at vertex A of the directed graph below

Depth-First Search Start from node 1 What is a sequence of nodes which would be visited in DFS? 1 2 3 5 4

Depth-First Search DFS uses backtracking when necessary to return to some values that were already processed or skipped over on an earlier pass When tracking this with a stack pop returned item from the stack Recursion is also a natural technique for this task Note: DFS of a tree would be equivalent to a preorder traversal

Depth-First Search Algorithm to perform DFS search of digraph 1. Visit the start vertex, v 2. For each vertex w adjacent to v do: If w has not been visited, apply the depth-first search algorithm with w as the start vertex. Note the recursion

Breadth-First Search Start from a given vertex v Visit all neighbors of v Then visit all neighbors of first neighbor w of v Then visit all neighbors of second neighbor x of v … etc. BFS visits nodes by level

Trees The visitation order of two traversals; (a) depth first; (b) breadth first.

Breadth-First Traversal Algorithm for breadth-first traversal of nonempty graph beginning at a given vertex Algorithm getBreadthFirstTraversal(originVertex) vertexQueue = a new queue to hold neighbors traversalOrder = a new queue for the resulting traversal order Mark originVertex as visited traversalOrder.enqueue(originVertex) vertexQueue.enqueue(originVertex) while (!vertexQueue.isEmpty()) { frontVertex = vertexQueue.dequeue() while (frontVertex has an unvisited neighbor) { nextNeighbor = next unvisited neighbor of frontVertex Mark nextNeighbor as visited traversalOrder.enqueue(nextNeighbor) vertexQueue.enqueue(nextNeighbor) } } return traversalOrder A breadth-first traversal visits a vertex and then each of the vertex's neighbors before advancing

Breadth-First Traversal Fig. 29-10 (ctd.) A trace of a breadth-first traversal for a directed graph, beginning at vertex A.

Breadth-First Search Start from node 1 What is a sequence of nodes which would be visited in BFS? 1 2 3 5 4

Breadth-First Search While visiting each node on a given level store it so that we can return to it after completing this level so that nodes adjacent to it can be visited First node visited on given level should be First node to which we return What data structure does this imply? A queue

Breadth-First Search Algorithm for BFS search of a diagraph Visit the start vertex Initialize queue to contain only the start vertex While queue not empty do Remove a vertex v from the queue For all vertices w adjacent to v do: If w has not been visited then: Visit w Add w to queue

Graph Traversal Algorithm to traverse digraph must: visit each vertex exactly once BFS or DFS forms basis of traversal Mark vertices when they have been visited Initialize an array (vector) unvisited unvisited[i] false for each vertex i While some element of unvisited is false Select an unvisited vertex v Use BFS or DFS to visit all vertices reachable from v

Paths Routing problems – find an optimal path in a network a shortest path in a graph/digraph a cheapest path in a weighted graph/digraph Example – a directed graph that models an airline network vertices represent cities direct arcs represent flights connecting cities Task: find most direct route (least flights)

Paths Most direct route equivalent to finding length of shortest path finding minimum number of arcs from start vertex to destination vertex Search algorithm for this shortest path an easy modification of the breadth-first search algorithm

Shortest Path Algorithm Visit start and label it with a 0 Initialize distance to 0 Initialize a queue to contain only start While destination not visited and the queue not empty do: Remove a vertex v from the queue If label of v > distance, set distance++ For each vertex w adjacent to v If w has not been visited then Visit w and label it with distance + 1 Add w to the queue

Shortest Path Algorithm If destination has not been visited then display "Destination not reachable from start vertex" else Find vertices p[0] … p[distance] on shortest path as follows Initialize p[distance] to destination For each value of k ranging from distance – 1 down to 0 Find a vertex p[k] adjacent to p[k+1] with label k

Shortest Path in an Unweighted Graph Fig. 29-15 (a) an unweighted graph and (b) the possible paths from vertex A to vertex H.

Shortest Path of an Unweighted Graph Algorithm getShortestPath(originVertex, endVertex) done = false vertexQueue = a new queue to hold neighbors Mark originVertex as visited vertexQueue.enqueue(originVertex) while (!done && !vertexQueue.isEmpty()) { frontVertex = vertexQueue.dequeue() while (!done && frontVertex has an unvisited neighbor) { nextNeighbor = next unvisited neighbor of frontVertex Mark nextNeighbor as visited Set the length of the path to nextNeighbor to 1 + length of path to frontVertex Set the predecessor of nextNeighbor to frontVertex vertexQueue.enqueue(nextNeighbor) if (nextNeighbor equals endVertex) done = true } } // traversal ends - construct shortest path path = a new stack of vertices path.push(endVertex) while (endVertex has a predecessor) endVertex = predecessor of endVertex return path Shortest Path of an Unweighted Graph

Shortest Path in an Unweighted Graph Fig. 29-16 The graph in 29-15a after the shortest-path algorithm has traversed from vertex A to vertex H

Shortest Path in an Unweighted Graph Fig. 29-17 Finding the shortest path from vertex A to vertex H in the unweighted graph in Fig. 29-15a.

Shortest Path in an Weighted Graph Fig. 29-18 (a) A weighted graph and (b) the possible paths from vertex A to vertex H.

Shortest Path of a Weighted Graph Algorithm getCheapestPath(originVertex, endVertex) done = false vertexQueue = a new priority queue vertexQueue.add(new PathEntry(originVertex, 0, null)); while (!done && !vertexQueue.isEmpty()) { frontEntry = vertexQueue.remove() frontVertex = vertex in frontEntry if (frontVertex is unvisited) Mark frontVertex as visited Set cost of path to frontVertex to cost in frontEntry Set the predecessor of frontVertex to the predecessor in frontEntry if (frontVertex equals endVertex) done = true else while (frontVertex has an unvisited neighbor) nextNeighbor = next unvisited neighbor of frontVertex edgeWeight = weight of edge to nextNeighbor nextCost = edgeWeight + cost of path to frontVertex vertexQueue.add(new PathEntry(nextNeighbor, nextCost, frontVertex)); } // traversal ends; construct cheapest path path = a new stack of vertices path.push(endVertex) while (endVertex has a predecessor) endVertex = predecessor of endVertex return path Shortest Path of a Weighted Graph

Shortest Path in an Weighted Graph Shortest path between two given vertices Smallest edge-weight sum Algorithm based on breadth-first traversal Several paths in a weighted graph might have same minimum edge-weight sum Algorithm given by text finds only one of these paths

Shortest Path in an Weighted Graph Fig. 29-19 Finding the cheapest path from vertex A to vertex H in the weighted graph in Fig 29-18a.

Shortest Path in an Weighted Graph Fig. 29-20 The graph in Fig. 29-18a after finding the cheapest path from vertex A to vertex H.

Undirected Graphs No direction is associated with the edges No loops joining a vertex to itself 1 A 2 B 5 E D 4 3 C e1 e2 e3 e4 e5 e6 1 2 3 5 4 Digraph Undirected graph

Undirected Graphs Undirected graphs are useful for modeling electrical circuits structures of chemical compounds communication systems any network in which link direction is unneeded As ADTs, graphs and digraphs have basically the same operations BSF and DFS apply equally well to both

Undirected Graph Representation Can be represented by adjacency matrices adjacency lists Adjacency matrix will always be symmetric For an edge from i to j, there must be An edge from j to i Hence the entries on one side of the matrix diagonal are redundant Since no loops, the diagonal will be all 0's Adjacency matrix is inefficient

Edge Lists Adjacency lists suffer from the same redundancy undirected edge is repeated twice More efficient solution use edge lists Consists of a linkage of edge nodes one for each edge to the two vertices that serve as the endpoints

Edge Nodes Each edge node represents one edge vertex[1] and vertex[2] are vertices connected by this edge link[1] points to another edge node having vertex[1] as one end point link[2] points to another edge node having vertex[2] as an endpoint vertex [1] vertex[2] link[1] link[2]

Edge List Vertices have pointers to one edge 1 A 2 B e1 e3 e2 e6 3 C

Edge List This representation consists of An array (vector) v of class objects one for each vertex Each class instance contains a data member a pointer to an edge node which contains that vertex as one of the endpoints

Graph Algorithms DFS, BFS, traversal, and other algorithms for processing graphs similar to those for digraphs DFS used to determine whether a graph is connected a path exists from each vertex to every other Note the graph class template page 739, Figure 14.2

Exercise for Page 734 B A D C F J E I K H G BFS Algorithm DFS Algorithm