Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root...

54
Graphs and Digraphs Chapter 14

Transcript of Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root...

Page 1: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

Graphs and Digraphs

Chapter 14

Page 2: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

2

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

Page 3: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

3

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

1

2

3

5

4

VerticesVerticesEdgesEdges

Page 4: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

4

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

Page 5: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

5

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

Page 6: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

6

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

Page 7: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

7

Graph Representation

• The adjacency matrixfor the digraph at theright is

1

2

3

5

41 2 3 4 5

1 0 1 1 0 1

2 0 0 1 0 0

3 0 0 0 1 0

4 0 0 1 0 0

5 0 0 0 0 0

rows i

columns j

• Entry [ 1, 5 ] set to true

• Edge from vertex 1 to vertex 5

• Entry [ 1, 5 ] set to true

• Edge from vertex 1 to vertex 5

Page 8: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

8

Graph Representation

• Weighted digraph– 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

Page 9: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

9

Weights

A weighted graph.

Page 10: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

10

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? _____

Page 11: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

11

Adjacency Matrix

• Consider the sum of the products of the pairs of elements from row i and column j

1 2 3 4 5

1 0 1 1 0 1

2 0 0 1 0 0

3 0 0 0 1 0

4 0 0 1 0 0

5 0 0 0 0 0

1

1

1 2 3 4 5

1 1

2

3

4

5

adj adj 2

Fill in the rest of adj 2

Fill in the rest of adj 2

This is the number of paths of length 2 from

node 1 to node 3

This is the number of paths of length 2 from

node 1 to node 3

Page 12: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

12

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

Page 13: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

13

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 matrix is sparse.

Page 14: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

14

Adjacency List

The node

The edges

The collection of nodes with accompanying

edges

Page 15: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

15

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)

Page 16: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

16

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

Page 17: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

17

Trees

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

Page 18: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

18

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

Page 19: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

19

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

Page 20: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

20

Depth-First SearchAlgorithm getDepthFirstTraversal(originVertex)

vertexStack = a new stack to hold vertices as they are visitedtraversalOrder = a new queue for the resulting traversal orderMark originVertex as visitedtraversalOrder.enqueue(originVertex)vertexStack.push(originVertex)while (!vertexStack.isEmpty()){ topVertex = vertexStack.peek()

if (topVertex has an unvisited neighbor){nextNeighbor = next unvisited neighbor of topVertexMark nextNeighbor as visitedtraversalOrder.enqueue(nextNeighbor)vertexStack.push(nextNeighbor)}

else // all neighbors are visitedvertexStack.pop()}

return traversalOrder

Page 21: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

21

Depth-First TraversalA trace of a depth-first traversal

beginning at vertex A of the directed graph

below

Page 22: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

22

Depth-First Search

• Start from node 1

• What is a sequence of nodes which would be visited in DFS?

1

2

3

5

4

Page 23: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

23

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

Page 24: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

24

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 algorithmwith w as the start vertex.

Note the recursionNote the recursion

Page 25: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

25

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

Page 26: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

26

Trees

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

Page 27: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

27

Breadth-First Traversal• Algorithm for breadth-first traversal of nonempty

graph beginning at a given vertexAlgorithm getBreadthFirstTraversal(originVertex)vertexQueue = a new queue to hold neighborstraversalOrder = a new queue for the resulting traversal orderMark originVertex as visitedtraversalOrder.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 visitedtraversalOrder.enqueue(nextNeighbor)vertexQueue.enqueue(nextNeighbor)

}}return traversalOrder

A breadth-first traversal visits a vertex and then each of the

vertex's neighbors before advancing

A breadth-first traversal visits a vertex and then each of the

vertex's neighbors before advancing

Page 28: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

28

Breadth-First TraversalFig. 29-10 (ctd.)

A trace of a breadth-first

traversal for a directed graph,

beginning at vertex A.

Page 29: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

29

Breadth-First Search

• Start from node 1

• What is a sequence of nodes which would be visited in BFS?

1

2

3

5

4

Page 30: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

30

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 beFirst node to which we return

What data structure does this imply?

A queueA queue

Page 31: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

31

Breadth-First Search

Algorithm for BFS search of a diagraph1. Visit the start vertex2. Initialize queue to contain only the start

vertex3. While queue not empty do

a. Remove a vertex v from the queueb. For all vertices w adjacent to v do:

If w has not been visited then:i. Visit wii. Add w to queue

Page 32: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

32

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

1. Initialize an array (vector) unvisitedunvisited[i] false for each vertex i

2. While some element of unvisited is falsea. Select an unvisited vertex vb. Use BFS or DFS to visit all vertices

reachable from v

Page 33: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

33

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)

Page 34: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

34

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

Page 35: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

35

Shortest Path Algorithm

1. Visit start and label it with a 02. Initialize distance to 03. Initialize a queue to contain only start4. While destination not visited and the

queue not empty do:a. Remove a vertex v from the queueb. If label of v > distance, set distance++c. For each vertex w adjacent to v

If w has not been visited theni. Visit w and label it with distance + 1ii. Add w to the queue

Page 36: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

36

Shortest Path Algorithm

5. 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

a. Initialize p[distance] to destination

b. For each value of k ranging from distance – 1 down to 0Find a vertex p[k] adjacent to p[k+1] with label k

Page 37: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

37

Shortest Path in an Unweighted Graph

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

Page 38: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

38Algorithm getShortestPath(originVertex, endVertex)done = falsevertexQueue = a new queue to hold neighborsMark originVertex as visitedvertexQueue.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 visitedSet the length of the path to nextNeighbor to 1 + length of path to

frontVertexSet the predecessor of nextNeighbor to frontVertexvertexQueue.enqueue(nextNeighbor)if (nextNeighbor equals endVertex)done = true

}} // traversal ends - construct shortest pathpath = a new stack of verticespath.push(endVertex)while (endVertex has a predecessor){

endVertex = predecessor of endVertexpath.push(endVertex)

}return path

Shortest Path of an Unweighted Graph

Shortest Path of an Unweighted Graph

Page 39: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

39

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

Page 40: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

40

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.

Page 41: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

41

Shortest Path in an Weighted Graph

Fig. 29-18 (a) A weighted graph and (b) the possible paths from vertex A to vertex H.

Page 42: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

42Algorithm getCheapestPath(originVertex, endVertex)done = falsevertexQueue = a new priority queuevertexQueue.add(new PathEntry(originVertex, 0, null));while (!done && !vertexQueue.isEmpty()){

frontEntry = vertexQueue.remove()frontVertex = vertex in frontEntryif (frontVertex is unvisited){

Mark frontVertex as visitedSet cost of path to frontVertex to cost in frontEntrySet the predecessor of frontVertex to the predecessor in frontEntryif (frontVertex equals endVertex)

done = trueelse{

while (frontVertex has an unvisited neighbor){nextNeighbor = next unvisited neighbor of frontVertexedgeWeight = weight of edge to nextNeighbornextCost = edgeWeight + cost of path to frontVertexvertexQueue.add(new PathEntry(nextNeighbor, nextCost,frontVertex));

} }

}// traversal ends; construct cheapest pathpath = a new stack of verticespath.push(endVertex)while (endVertex has a predecessor){

endVertex = predecessor of endVertexpath.push(endVertex)

}return path

Shortest Path of a Weighted Graph

Shortest Path of a Weighted Graph

Page 43: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

43

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

Page 44: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

44

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.

Page 45: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

45

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.

Page 46: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

46

Undirected Graphs

• No direction is associated with the edges

• No loops joining a vertex to itself

1

2

3

5

4

DigraphDigraph

Undirected graphUndirected graph

1A

2B

5E

D4

3C

e1

e2

e3

e4e5

e6

Page 47: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

47

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

Page 48: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

48

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

Page 49: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

49

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

Page 50: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

50

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 havingvertex[2] as anendpoint

vertex [1] vertex[2]

link[1] link[2]

Page 51: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

51

Edge List

• Vertices have pointers to one edge

1A

2B

5E

D4

3C

e1

e2

e3

e4e5

e6

Page 52: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

52

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

Page 53: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

53

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

Page 54: Graphs and Digraphs Chapter 14. 2 Graphs General graphs differ from trees –need not have a root node –no implicit parent-child relationship –may be several.

54

Exercise for Page 734

CA

B

D

E F J

H G I K

DFS AlgorithmBFS Algorithm