dschap11
TRANSCRIPT
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 2/53
Chapter Objectives
Data Structures Using Java2
y Learn about graphs
y Become familiar with the basic terminology of graph theory
y Discover how to represent graphs in computer memory
y Explore graphs as ADTsy Examine and implement various graph traversal algorithms
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 3/53
Chapter Objectives
Data Structures Using Java3
y Learn how to implement the shortest path algorithm
y Examine and implement the minimal spanning tree
algorithm
yExplore the topological sort
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 4/53
Königsberg Bridge Problem
Data Structures Using Java4
In 1736, the following problem was posed:
y River Pregel (Pregolya) flows around the island Kneiphof
y Divides into twoy River has four land areas ( A, B,C , D)
y Bridges are labeled a, b, c, d , e, f , g
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 5/53
Graphs
Data Structures Using Java5
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 6/53
Königsberg Bridge Problem
Data Structures Using Java6
y The Königsberg bridge problem
y Starting at one land area, is it possible to walk across all the bridges exactly
once and return to the starting land area?
y In 1736, Euler represented Königsberg bridge problem as graph;
Answered the question in the negative.
y This marked (as recorded) the birth of graph theory.
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 7/53
Graphs
Data Structures Using Java7
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 8/53
Graph Definitions and Notations
Data Structures Using Java8
y A graph G is a pair, g = (V , E), where V is a finite nonempty
set, called the set of vertices of G, and E V x V
y Elements of E are the pair of elements of V . E is called the set
of e
dge
s
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 9/53
Graph Definitions and Notations
Data Structures Using Java9
y Let V (G) denote the set of vertices, and E(G) denote the set
of edges of a graph G. If the elements of E(G) are ordered
pairs, g is called a directed graph or digraph; Otherwise, g is
called an undirected graph
y In an undirected graph, the pairs (u, v ) and (v , u) represent
the same edge
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 10/53
Various Undirected Graphs
Data Structures Using Java10
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 11/53
Various Directed Graphs
Data Structures Using Java11
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 12/53
Graph Representation: Adjacency
Matrix
y Let G be a graph with n vertices, where n > 0
y Let V (G) = {v 1, v 2, ..., v n}
y The adjacency matrix AG is a two-dimensional n × n matrixsuch that the (i, j)th entry of AG is 1 if there is an edge from
v i to v j; otherwise, the (i, j)th entry is zero
Data Structures Using Java12
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 13/53
Graph Representation: Adjacency
Matrix
Data Structures Using Java13
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 14/53
Graph Representation:
Adjacen
cy Lists
Data Structures Using Java14
y In adjacency list representation, corresponding to eachvertex, v , is a linked list such that each node of the linked listcontains the vertex u, such that (v , u) E(G)
y Array, A, of size n, such that A[i] is a ref erence variable pointing to address of first node of linked list containing the vertices to which v i is adjacent
y Each node has two components, (vertex and link)
y Component vertex contains index of vertex adjacent tovertex i
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 15/53
Graph Representation:
Adjacency List
Data Structures Using Java15
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 16/53
Graph Representation: Adjacency
Matrix
Data Structures Using Java16
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 17/53
Operations on Graphs
Data Structures Using Java17
y Create the graph: store in memory using a particular graph
representation
y Clear the graph: make the graph empty
y
Determine whether the graph is emptyy Traverse the graph
y Print the graph
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 18/53
class LinkedListGraph
Data Structures Using Java18
public class LinkedListGraph extends UnorderedLinkedList
{
//default constructor
public LinkedListGraph()
{
super();
}
//copy constructor public LinkedListGraph(LinkedListGraph otherGraph)
{
super(otherGraph);
}
//Method to retrieve the vertices adjacent to a given
//vertex.
//Postcondition: The vertices adjacent to a given
// vertex from linked list are retrieved // in the array adjacencyList.
// The number of vertices are returned.
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 19/53
class LinkedListGraph (continued)
Data Structures Using Java19
public int getAdjacentVertices(DataElement[] adjacencyList)
{
LinkedListNode current;
int length = 0;current = first;
11
while(current != null)
{
adjacencyList[len++] = current.info.getCopy();
current = current.link;
}
return length;}
}
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 20/53
Graph Traversals
Data Structures Using Java20
y Depth first traversal
y Mark node v as visited
y Visit the node
y For each vertex u adjacent to v
y If u is not visited
y Start the depth first traversal at u
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 21/53
Depth First Traversal
Data Structures Using Java21
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 22/53
Breadth First Traversal
Data Structures Using Java22
The general algorithm is:a. for each vertex v in the graph
if v is not visited
add v to the queue //start the breadth// first search at v
b. Mark v as visited c. while the queue is not empty
c.1. Remove vertex u from the queue
c.2. Retrieve the vertices adjacent to u
c.3. for each vertex w that is adjacent to u
if w is not visited
c.3.1. Add w to the queue
c.3.2. Mark w as visited
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 23/53
Shortest Path Algorithm
Data Structures Using Java23
y Weight of the edge: edges connecting two vertices can be assigned a nonnegative real number
y Weight of the path P: sum of the weights of all the edges on
the path P ;Weight of v from u via P
y Shortest path: path with smallest weight
y Shortest path algorithm: greedy algorithm developed byDijkstra
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 24/53
Shortest Path Algorithm
Data Structures Using Java24
Let G be a graph with n vertices, where n > 0.
Let V (G) = {v 1, v 2, ..., v n}. Let W be a
two-dimensional n X n matrix such that:
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 25/53
Shortest Path
Data Structures Using Java25
The
ge
ne
ral algorithm is:
1. Initialize the array smallestWeight so that
smallestWeight[u] = weights[vertex, u]
2. Set smallestWeight[vertex] = 0
3. Find the vertex, v, that is closest to vertex for which
the shortest path has not been determined 4. Mark v as the (next) vertex for which the smallest weight
is found
5. For each vertex w in G, such that the shortest path from vertex to w has not been determined and an edge (v, w)exists, if the weight of the path to w via v is smallerthan its current weight, update the weight of w to the
weight of v + the weight of the edge (v, w)
Because there are n vertices, repeat steps 3 through 5 n ² 1times
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 26/53
Shortest Path
Data Structures Using Java26
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 27/53
Shortest Path
Data Structures Using Java27
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 28/53
Shortest Path
Data Structures Using Java28
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 29/53
Shortest Path
Data Structures Using Java29
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 30/53
Minimal Spanning Tree
Data Structures Using Java30
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 31/53
Min
imalS
pann
in
g Tree
Data Structures Using Java31
y A company needs to shut down the maximum number of
connections and still be able to fly from one city to another
(may not be directly).
ySee Figure 11-14
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 32/53
Minimal Spanning Tree
Data Structures Using Java32
y (Free) tree T : simple graph such that if u and v are twovertices in T , then there is a unique path from u to v
y
Roote
d tree
: tree
in whic
h a partic
ular ve
rte
x is de
signate
das a root
y Weighted tree: tree in which weight is assigned to the edgesin T
y If T is a weighted tree, the weight of T , denoted by W (T ), is
the sum of the weights of all the edges in T
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 33/53
Minimal Spanning Tree
Data Structures Using Java33
y A tree T is called a spanning tree of graph G if T is a subgraph
of G such that V (T ) = V (G),
yAll the vertices of G are in T .
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 34/53
Minimal Spanning Tree
Data Structures Using Java34
y Theorem: A graph G has a spanning tree if and only if G is
connected.
yIn order to determine a spanning tree of a graph, the graphmust be connected.
y Let G be a weighted graph.A minimal spanning tree of G is a
spanning tree with the minimum weight.
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 35/53
Prim·s Algorithm
Data Structures Using Java35
y Builds tree iteratively by adding edges until minimal spanning
tree obtained
yStart with a source vertex
y At each iteration, new edge that does not complete a cycle is
added to tree
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 36/53
Prim·s Algorithm
Data Structures Using Java36
General form of Prim·s algorithm (let n = number of vertices in G):
1. Set V(T) = {source}
2. Set E(T) = empty
3. for i = 1 to n3.1 minWeight = infinity;
3.2 for j = 1 to n
if vj is in V(T)
for k = 1 to n
if vk is not in T and weight[vj][vk] < minWeight
{endVertex = vk;
edge = (vj, vk);
minWeight = weight[vj][vk];
}
3.3 V(T) = V(T) {endVertex};
3.4 E(T) = E(T) {edge};
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 37/53
Prim·s Algorithm
Data Structures Using Java37
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 38/53
Prim·s Algorithm
Data Structures Using Java38
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 39/53
Prim·s Algorithm
Data Structures Using Java39
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 40/53
Prim·s Algorithm
Data Structures Using Java40
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 41/53
Prim·s Algorithm
Data Structures Using Java41
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 42/53
Spanning Tree as an ADT
Data Structures Using Java42
Class: MSTree
public MSTree extends Graph
Instance Variables:
protected int source;
protected double[][] weights;
protected int[] edges;
protected double[] edgeWeights;
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 43/53
Spanning Tree as an ADT
Data Structures Using Java43
Constructors and Instance Methods:
public MSTree() //default constructor
public MSTree(int size)
//constructor with a parameter
public void createSpanningGraph()
throws IOException, FileNotFoundException
//Method to create the graph and the weight matrix.
public void minimalSpanning(int sVertex)
//Method to create the edges of the minimal
//spanning tree. The weight of the edges is also
//saved in the array edgeWeights.
public void printTreeAndWeight()
//Method to output the edges of the minimal
//spanning tree and the weight of the minimal
//spanning tree.
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 44/53
Topological Order
Data Structures Using Java44
y Let G be a directed graph and V (G) = {v 1, v 2, ..., v n}, where
n > 0.
y A topological ordering of V (G) is a linear ordering v i1, v i2, ...,
v
in
of the vertices such that if v ij
is a predecessor of v ik
, j k, 1
<= j <= n, and 1 <= k <= n, then v ij precedes v ik, that is, j
< k in this linear ordering.
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 45/53
Topological Order
Data Structures Using Java45
y Because the graph has no cycles:
y There exists a vertex u in G such that u has no predecessor.
y There exists a vertex v in G such that v has no successor.
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 46/53
Topological Order
Data Structures Using Java46
Class: TopologicalOrder
class TopologicalOrder extends Graph
Constructors and Instance Methods:
public void bfTopOrder()
//output the vertices in breadth first topological order
public TopologicalOrder(int size)
//constructor with a parameter
public TopologicalOrder()//default constructor
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 47/53
Breadth First Topological Order
Data Structures Using Java47
1. Create the array predCount and initialize it so that
predCount[i] is the number of predecessors of the vertex
vi
2. Initialize the queue, say queue, to all those vertices vk so
that predCount[k] is zero. (Clearly, queue is not empty
because the graph has no cycles.)
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 48/53
Breadth First Topological Order
Data Structures Using Java48
3. while the queue is not empty
A. Remove the front element, u, of the queue
B. Put u in the next available position, say
topologicalOrder[topIndex], and increment topIndex
C. For all the immediate successors w of u
1. Decrement the predecessor count of w by 1
2. if the predecessor count of w is zero, add w to queue
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 49/53
Breadth First Topological Order
Data Structures Using Java49
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 50/53
Breadth First Topological Order
Data Structures Using Java50
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 51/53
Breadth First Topological Order
Data Structures Using Java51
5/12/2018 DSchap11 - slidepdf.com
http://slidepdf.com/reader/full/dschap11 52/53
Breadth First Topological Order
Data Structures Using Java52