Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Graphs and Digraphs Chapter 14

2 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

3 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 Vertices Edges

4 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

5 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

6 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

7 7 Graph Representation The adjacency matrix for the digraph at the right is 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

8 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

9 9 Weights A weighted graph.

10 10 Adjacency Matrix Out-degree of i th vertex (node) –Sum of 1's (true's) in row i In-degree of j th 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? _____

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

12 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

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

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

15 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)

16 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

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

18 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

19 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

20 20 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

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

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

23 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

24 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: Ifwhas not been visited, apply the depth-first search algorithm withwas the start vertex. Note the recursion

25 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

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

27 27 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

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

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

30 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 be First node to which we return What data structure does this imply? A queue

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

32 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) unvisited unvisited[i] false for each vertex i 2.While some element of unvisited is false a.Select an unvisited vertex v b.Use BFS or DFS to visit all vertices reachable from v

33 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)

34 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

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

36 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 0 Find a vertex p [ k ] adjacent to p [ k+1 ] with label k

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

38 38 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 path.push(endVertex) } return path Shortest Path of an Unweighted Graph

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

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

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

42 42 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 path.push(endVertex) } return path Shortest Path of a Weighted Graph

43 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

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

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

46 46 Undirected Graphs No direction is associated with the edges No loops joining a vertex to itself Digraph Undirected graph 1A1A 2B2B 5E5E D4D4 3C3C e1e1 e2e2 e3e3 e4e4 e5e5 e6e6

47 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

48 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

49 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

50 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 having vertex[2] as an endpoint vertex [1]vertex[2] link[1]link[2]

51 51 Edge List Vertices have pointers to one edge 1A1A 2B2B 5E5E D4D4 3C3C e1e1 e2e2 e3e3 e4e4 e5e5 e6e6

52 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

53 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

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


Download ppt "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."

Similar presentations


Ads by Google