Graphs
-
Upload
jacqueline-simon -
Category
Documents
-
view
17 -
download
0
description
Transcript of Graphs
GraphsGraphs
Chapter 13Chapter 13
CS 302 2Chapter 13 -- Graphs
PreviewPreview Graphs are an important mathematical concept that Graphs are an important mathematical concept that
have significant applications not only in computer have significant applications not only in computer science, but also in many other fields.science, but also in many other fields.
You can view a graph as a mathematical construct, You can view a graph as a mathematical construct, a data structure, or an abstract data type.a data structure, or an abstract data type.
This chapter provides an introduction to graphs This chapter provides an introduction to graphs and it presents the major operations and and it presents the major operations and applications of graphs that are relevant to the applications of graphs that are relevant to the computer scientistcomputer scientist
CS 302 3Chapter 13 -- Graphs
TerminologyTerminology
Def: A graph G consists of two sets Def: A graph G consists of two sets VerticesVertices EdgesEdges
Def: AdjacentDef: Adjacent Two vertices are said to be adjacent if they are Two vertices are said to be adjacent if they are
joined by an edge.joined by an edge.
CS 302 4Chapter 13 -- Graphs
Def: SubgraphDef: Subgraph A subgraph consists of a set of a graph’s vertices A subgraph consists of a set of a graph’s vertices
and a subset of its edgesand a subset of its edges
CS 302 5Chapter 13 -- Graphs
Def: PathDef: Path A path between two vertices is a sequence of edges A path between two vertices is a sequence of edges
that begins at one vertex and ends at another.that begins at one vertex and ends at another. Simple path: does not pass through the same Simple path: does not pass through the same
vertex more than once.vertex more than once. Def: CycleDef: Cycle
A cycle is a path that begins and ends at the same A cycle is a path that begins and ends at the same vertex.vertex.
Def: ConnectedDef: Connected A graph is connected if each pair of distinct A graph is connected if each pair of distinct
vertices has a path between themvertices has a path between them
CS 302 6Chapter 13 -- Graphs
A graph is complete if each pair of distinct A graph is complete if each pair of distinct vertices has an edge between themvertices has an edge between them
CS 302 7Chapter 13 -- Graphs
Since a graph has a set of edges it cannot have Since a graph has a set of edges it cannot have duplicate edges. duplicate edges. However, a multigraph does allow multiple edgesHowever, a multigraph does allow multiple edges A graph also does not allow self-edges (loops)A graph also does not allow self-edges (loops)
CS 302 8Chapter 13 -- Graphs
You can label the edges of a graphYou can label the edges of a graph When these labels represent numeric values, the When these labels represent numeric values, the
graph is called a weighted graphgraph is called a weighted graph
CS 302 9Chapter 13 -- Graphs
All of the previous examples were of All of the previous examples were of undirected graphs, because the edges did not undirected graphs, because the edges did not indicate a direction. If there is direction, then indicate a direction. If there is direction, then the graph is called a directed graph (or the graph is called a directed graph (or digraph)digraph)
CS 302 10Chapter 13 -- Graphs
Graphs as ADTsGraphs as ADTs
Basic FunctionsBasic Functions Create, Destroy, Determine emptyCreate, Destroy, Determine empty Determine number of vertices and edgesDetermine number of vertices and edges Is there an edge between I and J?Is there an edge between I and J? Insert a vertex, or Insert an edgeInsert a vertex, or Insert an edge Delete a vertex, or Delete an EdgeDelete a vertex, or Delete an Edge ……
CS 302 11Chapter 13 -- Graphs
Implementing GraphsImplementing Graphs The two most common implementations of a graph The two most common implementations of a graph
are the Adjacency Matrix and the Adjacency Listare the Adjacency Matrix and the Adjacency List
Adjacency MatrixAdjacency Matrix Given a graph G with n verticesGiven a graph G with n vertices Matix is n x n of BooleansMatix is n x n of Booleans Entries – True if an edge exists between I and J (false Entries – True if an edge exists between I and J (false
otherwise).otherwise).
CS 302 12Chapter 13 -- Graphs
Example: a directed graph.Example: a directed graph.
CS 302 13Chapter 13 -- Graphs
Example: a weighted graphExample: a weighted graph
CS 302 14Chapter 13 -- Graphs
An Adjacency ListAn Adjacency List Given a graph G with n verticesGiven a graph G with n vertices N linked listsN linked lists The iThe ithth list has node for vertex j iff there is an edge list has node for vertex j iff there is an edge
between i and jbetween i and j
CS 302 15Chapter 13 -- Graphs
Example: a directed graphExample: a directed graph
CS 302 16Chapter 13 -- Graphs
Example: a weighted graphExample: a weighted graph
CS 302 17Chapter 13 -- Graphs
Which implementation is better?Which implementation is better? Let’s look at the two most common operationsLet’s look at the two most common operations
Determine if there is an edge (i, j)Determine if there is an edge (i, j) Find all vertices adjacent to a given vertex i.Find all vertices adjacent to a given vertex i.
The adjacency matrix supports the first one The adjacency matrix supports the first one somewhat more efficiently than the listsomewhat more efficiently than the list
The second operation is supported more efficiently The second operation is supported more efficiently by the adjacency list than the matrix.by the adjacency list than the matrix.
CS 302 18Chapter 13 -- Graphs
Now consider the space requirementsNow consider the space requirements
CS 302 19Chapter 13 -- Graphs
Graph TraversalsGraph Traversals
Visit all the vertices in the graph.Visit all the vertices in the graph. There are two major ways to do this:There are two major ways to do this:
Depth first searchDepth first search Breadth first searchBreadth first search
CS 302 20Chapter 13 -- Graphs
Example: the order in which the nodes of a tree are Example: the order in which the nodes of a tree are visited in a depth-first search and a breadth-first visited in a depth-first search and a breadth-first search.search.
CS 302 21Chapter 13 -- Graphs
How do you implement them?How do you implement them? Depth-First SearchDepth-First Search
Typically done with a stack.Typically done with a stack. Breadth-First SearchBreadth-First Search
Typically done with a QueueTypically done with a Queue
CS 302 22Chapter 13 -- Graphs
Example: DFSExample: DFS Start with Node aStart with Node a
Trace the SearchTrace the Search
CS 302 23Chapter 13 -- Graphs
Example: DFSExample: DFS
CS 302 24Chapter 13 -- Graphs
Example: BFSExample: BFS Start with Node aStart with Node a
Trace the SearchTrace the Search
CS 302 25Chapter 13 -- Graphs
Example: BFSExample: BFS
CS 302 26Chapter 13 -- Graphs
Applications of GraphsApplications of Graphs
Topological SortingTopological Sorting Given the following graph, place the vertices in Given the following graph, place the vertices in
order so that the edges all point in one directionorder so that the edges all point in one direction
CS 302 27Chapter 13 -- Graphs
Multiple solutions:Multiple solutions:
Applications: Prerequisites ( 201,202,236,336,308,…)Applications: Prerequisites ( 201,202,236,336,308,…)
CS 302 28Chapter 13 -- Graphs
Spanning TreesSpanning Trees Given a graph G, construct a tree that has all the Given a graph G, construct a tree that has all the
vertices of Gvertices of G
CS 302 29Chapter 13 -- Graphs
A few observations about undirected graphsA few observations about undirected graphs A connected undirected graph that has n vertices must A connected undirected graph that has n vertices must
have at least n-1 edgeshave at least n-1 edges A connected undirected graph that has n vertices and A connected undirected graph that has n vertices and
exactly n-1 edges cannot contain a cycle.exactly n-1 edges cannot contain a cycle. A connected undirected graph that has n vertices and A connected undirected graph that has n vertices and
more than n-1 edges must contain at least 1 cycle.more than n-1 edges must contain at least 1 cycle.
CS 302 30Chapter 13 -- Graphs
The DFS Spanning TreeThe DFS Spanning Tree
CS 302 31Chapter 13 -- Graphs
The BFS spanning TreeThe BFS spanning Tree
CS 302 32Chapter 13 -- Graphs
Minimum Spanning TreesMinimum Spanning Trees Given a weighted undirected graph, compute the Given a weighted undirected graph, compute the
spanning tree with the minimum costspanning tree with the minimum cost
CS 302 33Chapter 13 -- Graphs
Prim’s AlgorithmPrim’s Algorithm Start with two setsStart with two sets
Vertices not visited (not part of the tree)Vertices not visited (not part of the tree) Vertices visited (part of the tree – initialized to some start Vertices visited (part of the tree – initialized to some start
vertex)vertex)
Find the shortest edge from the visited set to the not Find the shortest edge from the visited set to the not visited set.visited set.
Add the edge to the MSTAdd the edge to the MST Move the vertex on the other end from not visited to visited.Move the vertex on the other end from not visited to visited.
Continue until all vertices are visited.Continue until all vertices are visited.
CS 302 34Chapter 13 -- Graphs
Trace of Prim’sTrace of Prim’s
CS 302 35Chapter 13 -- Graphs
CS 302 36Chapter 13 -- Graphs
CS 302 37Chapter 13 -- Graphs
Shortest PathsShortest Paths Consider once again a map of airline routes.Consider once again a map of airline routes. The shortest path from 0 to 1 in the following The shortest path from 0 to 1 in the following
graph is not the edge 0-1 (weight 8) but the path graph is not the edge 0-1 (weight 8) but the path (0-4-2-1)(0-4-2-1)
CS 302 38Chapter 13 -- Graphs
The algorithm to calculate the answer is attributed The algorithm to calculate the answer is attributed to Dijkstrato Dijkstra
Need two arraysNeed two arrays Weight – Weight – Weight[v]Weight[v] = weight of the shortest path from 0 to v = weight of the shortest path from 0 to v Matrix – Matrix – Matrix[v][u]Matrix[v][u] = weight of edge from v to u = weight of edge from v to u
Then compare the Then compare the Weight[u]Weight[u] with with Weight[v]+Matrix[v][u].Weight[v]+Matrix[v][u]. Put the smallest in Put the smallest in Weight[u]Weight[u]
Then we need a set of vertices we have visitedThen we need a set of vertices we have visited
CS 302 39Chapter 13 -- Graphs
We begin with the vertex set initialized to 0We begin with the vertex set initialized to 0
CS 302 40Chapter 13 -- Graphs
CS 302 41Chapter 13 -- Graphs
CS 302 42Chapter 13 -- Graphs
CircuitsCircuits Eulerian CircuitsEulerian Circuits
Probably the first application of graphs occurred in the Probably the first application of graphs occurred in the early 1700s when Euler proposed the Königsberg bridge early 1700s when Euler proposed the Königsberg bridge problem. problem.
Can you start and end at the same point and only cross Can you start and end at the same point and only cross each bridge once? each bridge once?
CS 302 43Chapter 13 -- Graphs
Some Difficult ProblemsSome Difficult Problems The Traveling Salesperson ProblemThe Traveling Salesperson Problem
Def: A Hamiltonian circuit – pass through every vertex Def: A Hamiltonian circuit – pass through every vertex once.once.
Given Given a weighted graph a weighted graph an origin cityan origin city
Problem:Problem: the salesperson must begin at an origin city and visit all others the salesperson must begin at an origin city and visit all others
(exactly once) and return to the origin (exactly once) and return to the origin and do it with the least cost.and do it with the least cost.
CS 302 44Chapter 13 -- Graphs
The three utilities problemThe three utilities problem GivenGiven
A graph (3 houses, 3 utilities)A graph (3 houses, 3 utilities) ProblemProblem
Connect each house with each utility so the edges do not crossConnect each house with each utility so the edges do not cross
This is a planarity question (minimum crossing number = 0) This is a planarity question (minimum crossing number = 0) for Kfor K3,33,3
CS 302 45Chapter 13 -- Graphs
The four color problemThe four color problem GivenGiven
A planar graphA planar graph
ProblemProblem Can you color the vertices so no two adjacent vertices have the Can you color the vertices so no two adjacent vertices have the
same color?same color?
The question was posed more than a century ago (1852) The question was posed more than a century ago (1852) and was only solved in the 1976 (with the help of a and was only solved in the 1976 (with the help of a computer)computer)
Trivia: Nature July 17, 1879 carried a proof of this problem Trivia: Nature July 17, 1879 carried a proof of this problem (which was proved false in 1890)(which was proved false in 1890)
CS 302 46Chapter 13 -- Graphs
SummarySummary
Implementations:Implementations: Adjacency Matrix and Adjacency ListAdjacency Matrix and Adjacency List
Graph searching Graph searching uses stacks and Queuesuses stacks and Queues
TreesTrees Connected, undirected, acyclic graphsConnected, undirected, acyclic graphs
Problems looked atProblems looked at Shortest Paths, Eulerian circuits, Hamiltonian Shortest Paths, Eulerian circuits, Hamiltonian
CircuitsCircuits