Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Graphs 11
11.1 Definition
11.2 Representation of Graphs
11.3 Topological Sort
11.4 Shortest-Path Algorithms
11.5 MinimumSpanning Tree
11.6 Graph Traversals
11.7 Applications of graph
11.8 Summary
11.9 Key Terms
11.10 Review Questions
195
Chapter 11- Graphs
Objectives
To understand the concepts of graph and its applications
To solve the problem of finding the shortest path using dijkstra's algorithm
To construct the minimum spanning tree using Prim's and Kruskals's algorithm
11.1. Definition
A graph consists of a set of nodes (or Vertices) and a set of arc (or edges). Each arc in a graph
is specified by a pair of nodes. A node is incident to an arc x if n is one of the two nodes in the
ordered pair of nodes that constitute x. The degree of a node is the number of arcs incident to
it. The indegree of a node n is the number of arcs that have n as the head, and the outdegree of
n is the number of arcs that have n as the tail. Loop is an edge that connects a vertex to itself.
The graph is the nonlinear data structure. The graph shown in the figure 11.1 represents 7
vertices and 12 edges. The Vertices are {1,2,3,4,5,6,7} and the arcs are{(1,2),(1,3),
(1,4),(2,4),(2,5),(3,4),(3,6),(4,5),(4,6),(4,7),(5,7),(6,7)}. Node(4) in figure has indegree 3,
outdegree 3 and degree 6.
A directed graph is acyclic if it has no cycles. A directed acyclic graph is sometimes referred to
by its abbreviation, DAG.
An undirected graph is connected if there is a path from every vertex to every other vertex. A
directed graph with this property is called strongly connected. If a directed graph is not strongly
connected, but the underlying graph (without direction to the arcs) is connected, then the graph is
said to be weakly connected. A complete graph is a graph in which there is an edge between
every pair of vertices.
196
Chapter 11- Graphs
Two common ways to represent graphs on a computer are as an adjacency list or as an adjacency
matrix.
11.2.1. Adjacency Matrix Representation
One simple way to represent a graph is to use a two-dimensional array. This isknown as an
adjacency matrix representation. For each edge (u, v), we set a[u][v]= 1; otherwise the entry in
the array is 0. If the edge has a weight associatedwith it, then we can set a[u][v] equal to the
weight and use either a very largeor a very small weight as a sentinel to indicate nonexistent
edges.
AnadjacencymatrixofagraphG=(V,E)(letV={v1 ,v2 .....,vn})isanXn matrix A,such that
A[i, j]=1 ifthereis edgebetween vi and v j.
0 other wise
11.2.2. AdjacencyListRepresentation
Adjacency lists are the standard way to represent graphs. For each vertex, we keep a list ofall
adjacent vertices, whichcanberepresentedeitherbylinkedlistorarray. The space requirement is then
O|E| + |V|).
An example is given below.
197
Chapter 11- Graphs
Topological sort is a method of arranging the vertices in a directed acyclic graph (DAG), as
a sequence, such that no vertex appears in the sequence before its predecessor.
One way to find a topological sort is to consider in-degrees of the vertices.The first vertex
must have in-degree zero.
Every DAG must have at least one vertex with in-degree zero. Topological sort is not
unique.
The following are all topological sort of the graph below:
s1 = {a, b, c, d, e, f, g, h, i}
s2 = {a, c, b, f, e, d, h, g, i}
s3 = {a, b, d, c, e, g, f, h, i}
s4 = {a, c, f, b, e, h, d, g, i}
etc.
Figure 11.4 – Example graph and its ordering for Topological Sort
Example
198
Chapter 11- Graphs
Vertex 1 2 3 4 5 6 7
----------------------------------------------------------------------------
V1 0 0 0 0 0 0 0
V2 1 0 0 0 0 0 0
V3 2 1 1 1 0 0 0
V4 3 2 1 0 0 0 0
V5 1 1 0 0 0 0 0
V6 3 3 3 3 2 1 0
V7 2 2 2 1 0 0 0
---------------------------------------------------------------------------
Enqueue v1 v2 v5 v4 v3 v7 v6
---------------------------------------------------------------------------
Dequeue v1 v2 v5 v4 v3 v7 v6
Figure 11.6- Result of applying topological sort for the graph 11.5.
Algorithm
199
Chapter 11- Graphs
The shortest path problem is the problem of finding a path between two vertices (or nodes) in a
graph such that the sum of the weights of its constituent edges is minimized. This is analogous to
the problem of finding the shortest path between two intersections on a road map: the graph's
vertices correspond to intersections and the edges correspond to road segments, each weighted
by the length of its road segment. The algorithm used to find the shortest path is,
Unweighted Shortest Paths Algorithm
Dijkstra's Algorithm (Weighted Shortest Paths Algorithm)
Let G(V,E) be a unweighted graph. Given a source vertex s, find the shortest path to all other
vertices.The algorithm uses Breadth-first search in the graph: Take a vertex and examine all
adjacent vertices. Do the same with each of the adjacent vertices
200
Chapter 11- Graphs
V5: V7
V6: -
V7: V6
Let s = V3. The distance from V3 to V3 is 0.
Initially the distances to all other nodes are not computed,
and we initialize the first column in the distance table for all vertices (except V3) with -1
Steps
1. Store s in a queue and set the distance to s to be 0 in the Distance Table.
Initialize the distances to all other vertices as "not computed",
e.g. using a sentinel value ∞.
2. While there are vertices in the queue:
a. Read a vertex v from the queue
b. For all adjacent vertices w:
If distance to w is ∞ (not computed) do:
Make distance to w equal to (distance to v) + 1
Make path to w equal to v
Append w to the queue
Algorithm
201
Chapter 11- Graphs
T[w].path = v;
enqueue( w, Q );
}
}
dispose_queue( Q );
}
Complexity
The complexity for unweighted shortest path algorithm is:O(|E| + |V|). If we use
matrixrepresentation the complexity is O(|V|2), because we need to read an entire row in the
matrix of length |V| in order to find the adjacent vertices for a given vertex.
202
Chapter 11- Graphs
Steps
1. Store s in a priority queue with priority 0 and set distance to s to be 0 in the Distance
Table.
Initialize the distances to all other vertices as "not computed",
e.g. using a sentinel value -1.
2. While there are vertices in the queue:
a. DeleteMin a vertex v from the queue
b. For all adjacent vertices w do:
Compute new distance d= (distance to v) + weight(v,w)
If old distance (the distance stored in the Distance Table) is -1
(not computed) do:
store new distance d in Distance Table
insert w in the priority queue with priority d
store path = v
If old distance > new distance d
Update old distance = new distance d
Update priority of vertex w to be d
(this is done by updating the priority of an element in the queue -
decreaseKey operation. Complexity O(log|V|))
Update path to w to be v
Example
203
Chapter 11- Graphs
Algorithm
Dijkstra_shortest_path(G, v_0)
For each vertex vi in V do
dist[vi]=infinity
distance[v0]=0;
for each vertex v_i in V do
insert(Q,vi)
S = empty
while (Qnot empty) do
vi=Min(Q)
for each vertex vj adjacent to vi do
distance[vj]=Minimum(distance[vj],distance[vi]+w[vi,vj])
204
Chapter 11- Graphs
205
Chapter 11- Graphs
Each vertex is stored only once in the queue - max elements = |V|
The deleteMin operation is O( |V|log|V| )
The decreaseKey operation is O(log|V|) (a search in the binary heap).
It might be performed for each examined edge - O(|E|log|V|).
The minimum spanning tree of a weighted graph is a set of edges of minimum total weight
which form a spanning tree of the graph. When a graph is unweighted, any spanning tree is a
minimum spanning tree.
Definition
A tree is a connected graph without cycles is called Minimum spanning Tree.
Properties of Trees
° A graph is a tree if and only if there is one and only one path joining any two of its vertices.
° A connected graph is a tree if and only if every one of its edges is a bridge.
° A connected graph is a tree if and only if it has N vertices and N; 1 edges.
Other Definitions
° A subgraph that spans (reaches out to) all vertices of a graph is called a spanning subgraph.
° A subgraph that is a tree and that spans (reaches out to) all vertices of the original graph is
called a spanning tree.
° Among all the spanning trees of a weighted and connected graph, the one (possibly more) with
the least total weight is called a minimum spanning tree (MST).
206
Chapter 11- Graphs
Figure 11.13 – Graph and its Minimum Spanning Tree (Prim’s &Kruskal’s)
207
Chapter 11- Graphs
Algorithm
The algorithm continuously increases the size of a tree, one edge at a time, starting with a tree
consisting of a single vertex, until it spans all vertices.
208
Chapter 11- Graphs
An implementation of the algorithm can be done using a set data structure. Each component is
represented as a set. Add next least weighted edge (u,v), if u and v are in two different
components or sets. That is, make a bigger component by taking the union of the sets containing
u and v.
209
Chapter 11- Graphs
At the termination of the algorithm, the forest forms a minimum spanning forest of the graph. If
the graph is connected, the forest has a single component and forms a minimum spanning tree.
Data Structure
Make_SET(v): Create a new set whose only member is pointed to by v. Note that for
this operation v must already be in a set.
FIND_SET(v): Returns a pointer to the set containing v.
UNION(u, v): Unites the dynamic sets that contain u and v into a new set that is union
of these two sets.
Algorithm
KRUSKAL(G):
A=∅
foreach v ∈ G.V:
MAKE-SET(v)
foreach (u, v) ordered by weight(u, v), increasing:
if FIND-SET(u) ≠ FIND-SET(v):
A = A ∪ {(u, v)}
UNION(u, v)
return A
Analysis
The total running time of Kruskal’s Algorithm is O((V + E) log V), which is O(E log V) since
graph is simple and connected.
Many graph problems can be solved by visiting each and every vertex in a systematic manner.
There are two main methods to traversal graphs,
DepthFirstSearch(DFS)
BreadthFirstSearch (BFS)
11.6.1 DepthFirstSearch(DFS)
Depth-first search(DFS) is an algorithm for traversing or searching tree or graph data structures.
One starts at the root (selecting some node as the root in the graph case) and explores as far as
possible along each branch before backtracking.
210
Chapter 11- Graphs
Depth First Search (DFS) searches deeper into the problem space. Depth First Search uses last-in
first-out stack for keeping the unexpanded nodes. More commonly, depth-first search is
implemented recursively, with the recursion stack taking the place of an explicit node stack.
Steps
1.If the initial state is a goal state, quit and return success.
2.Otherwise, loop until success or failure is signaled.
a) Generate a state, say E, and let it be the successor of the initial state. If there is no
successor, signal failure.
b) Call Depth-First Search with E as the initial state.
c) If success is returned, signal success. Otherwise continue in this loop.
Algorithm
DFS (G)
fori =1 to n do
unvisited
parent[i]=NULL
fori =1 to n do
if(status[i] == unvisited)
DF-Travel(i)
DF-Travel(v )
status[v]=visited
for each vertexu adjacent to vdo
ifstatus[u]==unvisited then
parent[u]=v
DF-Travel (u)
211
Chapter 11- Graphs
3. If depth-first search finds solution without exploring much in a path then the time and
space it takes will be very less.
11.6.2 BreadthFirstSearch(BFS)
Breadth First Search (BFS) searches breadth-wise in the problem space. Breadth-First search is
like traversing a tree where each node is a state which may be a potential candidate for solution.
Breadth first search expands nodes from the root of the tree and then generates one level of the
tree at a time until a solution is found. It is very easily implemented by maintaining a queue of
nodes. Initially the queue contains just the root. In each iteration, node at the head of the queue is
removed and then expanded. The generated child nodes are then added to the tail of the queue.
Since it never generates a node in the tree until all the nodes at shallower levels have been
generated, breadth-first search always finds a shortest path to a goal. Since each node can be
generated in constant time, the amount of time used by Breadth first search is proportional to the
number of nodes generated, which is a function of the branching factor b and the solution d.
Since the number of nodes at level d is bd, the total number of nodes generated in the worst case
is b + b2 + b3 +… + bd i.e. O(bd) , the asymptotic time complexity of breadth first search.
212
Chapter 11- Graphs
Algorithm
1. Create a variable called NODE-LIST and set it to the initial state.
2. Loop until the goal state is found or NODE-LIST is empty.
a. Remove the first element, say E, from the NODE-LIST. If NODE-LIST was
empty then quit.
b. For each way that each rule can match the state described in E do:
i) Apply the rule to generate a new state.
ii) If the new state is the goal state, quit and return this state.
iii) Otherwise add this state to the end of NODE-LIST
213
Chapter 11- Graphs
Intuitively, one starts at the root nodes. Then for each of those nearest
(selecting some node as the root in nodes, it explores their unexplored
the graph case) and explores as far as neighbor nodes, and so on, until it
possible along each branch before finds the goal.
backtracking.
Data structure Uses stack Uses queue
Applications are finding articulation Applications are finding minimum
Application points, Euler circuits spanning tree, Dijkstra’s algorithm
Example
Undirected graph
Bi connectivity
Euler circuits
Directed graph
Finding strong components
214
Chapter 11- Graphs
Construct the DFS for the graph starts from the vertex A, it travers to B, then C, and then D. From
D there is no further vertex to visit, because vertices A & B are already visited. So move
backwards to C and then visit E. Now the resultant graph is shown in figure 11.19. In this example,
all the vertices starting from A are visited, so the above graph is said to be connected. If the graph
is not connected, then processing all nodes and edges requires several calls DFS, and each
generates a tree. This entire collection is called depth first spanning forest.
11.7.2 Biconnectivity
A connected undirected graph is biconnected if there are no vertices whose removal disconnects
the rest of the graph. The graph in the example is biconnected.
If a graph is not biconnected, the vertices whose removal would disconnect the rest of the graph
are called as articulation points. These nodes are critical in many applications. The graph shown
in figure 11.21 is not biconnected. The removal of C would disconnect G, and the removal of D
would disconnect E and F, from the rest of the graph. In this example, vertices C & D are the
articulation points.
Depth-first search provides a linear-time algorithm to find all articulation points in a connected
graph.
215
Chapter 11- Graphs
First, starting at any vertex, we perform a depth-first search and number the nodes as
they are visited.
For each vertex v, we call this preorder number num(v).
Then, for every vertex v in the depth-first search spanning tree, we compute the
lowest-numbered vertex, which we call low(v), that is reachable from v by taking zero
or more tree edges and then possibly one back edge (in that order). By the definition
of low, low(v) is the minimum of
1. num(v)
2. the lowest num(w) among all back edges (v, w)
3. the lowest low(w) among all tree edges (v, w)
The first condition is the option of taking no edges, the second way is to choose no tree edges
and a back edge, and the third way is to choose some tree edges and possibly a back edge. This
third method is succinctly described with a recursive call. Since we need to evaluate low for all
the children of v before we can evaluate low(v), this is a postorder traversal.
Algorithm
assign_low( w );
216
Chapter 11- Graphs
if(num[w] >num[v] )
{
assign_low( w );
if( low[w] >= num[v] )
printf( "%v is an articulation point\n", v );
low[v] = min( low[v], low[w] );
}
else
if( parent[v] != w )
low[v] = min( low[v], num[w] );
}
}
217
Chapter 11- Graphs
Example
Step1: Construct DFS for the graph starting from the source vertex A. Then the resultant graph
will be
Step 2: For each vertex v, we call this preorder number num(v). Assign the number for the
vertices in the order they are visited using DFS. Now the graph that has assigned a number for
the vertices as,
218
Chapter 11- Graphs
Step 3: Finding the low value for the vertices starting from the leaf node to the root node. For
any vertex v,
Low(v) is the minimum of
1. num(v)
2. the lowest num(w) among all back edges (v, w)
3. the lowest low(w) among all tree edges (v, w)
Take a vertex F for an example,
Low(F) = min { num(F), num(D)} /* since, there is no tree edge only one back edge
Low(F) = min { 6, 4} = 4
Then, take a vertex E,
Low(E) = min { num(E), low(F)} /* since, there is no back edge
Low(E) = min { 5, 4} = 4
Then take a vertex D,
Low(D) = min { num(D), low(E), num(A)} /* since, A is the back edge of D
Low(D) = min { 4, 4, 1 } = 1
Then take a vertex G before C.
Low(G) = min { num(G) } /* since, For G there is no tree edge and back edge
Low(G) = min { 7 } = 7
Now we take C,
219
Chapter 11- Graphs
Step 4: Apply an algorithm, finding the articulation points for the vertices that starts from the
root node to the leaf node. A, C & D are the vertices that satisfied the condition mentioned in the
algorithm. Now remove the root vertex from the set, we have the vertices C & D. So, for this
above graph, C & D are the articulation points.
220
Chapter 11- Graphs
one greater than in-degree (this is the start vertex), and the other vertex has in-degree
with one greater than out-degree (this is the end vertex).
Example
221
Chapter 11- Graphs
Figure 11.29 – Solution for Euler Circuit (Graph that starts from 1 then moves towards
3,2,8,9,3,4,5,10,4,7,3,6,9,7,10,9,12,10,11,4,1)
222
Chapter 11- Graphs
there are 2s edges having v as an endpoint.Therefore, all vertices other than the two endpoints
ofP must be even vertices.
Complexity
The complexity of both algorithms is O(N+M), where N is the number of vertices and M is the
number of edges.
The dashed arrows in the depth-first spanning forest are edges (v, w) for which w was
alreadymarked at the time of consideration. In undirected graphs, these are always back edges,
223
Chapter 11- Graphs
but, aswe can see, there are three types of edges that do not lead to new vertices. First, there
areback edges, such as (A, B) and (I, H). There are also forward edges, such as (C, D) and (C,
E),that lead from a tree node to a descendant. Finally, there are cross edges, such as (F, C)
and(G, F), which connect two tree nodes that are not directly related. Depth-first search
forestsare generally drawn with children and new trees added to the forest from left to right. In
adepth- first search of a directed graph drawn in this manner, cross edges always go from right
toleft.
One use of depth-first search is to test whether or not a directed graph is acyclic. The rule isthat a
directed graph is acyclic if and only if it has no back edges. (The graph above has backedges, and
thus is not acyclic.)
The above directed graph has 4 strongly connected components: C1, C2, C3 and C4. If G has an
edge from some vertex in Ci to some vertex in Cj where i ≠ j, then one can reach any vertex in Cj
from any vertex in Ci but not return. In the example, one can reach any vertex in C 2 from any
vertex in C1 but cannot return to C1 from C2.
224
Chapter 11- Graphs
Algorithm
A DFS(G) produces a forest of DFS-trees. Let C be any strongly connected component of G, let
v be the first vertex on C discovered by the DFS and let T be the DFS-tree containing v when
DFS-visit(v) is called all vertices in C are reachable from v along paths containing visible
vertices; DFS-visit(v) will visit every vertex in C, add it to T as a descendant of v.
Strongly-connected-components (G)
11.8 Summary
In this chapter we have seen how graphs can be used to model many real-life problems. Many of
thegraphs that occur are typically very sparse, so it is important to pay attention to the
datastructures that are used to implement them.
Graph, adjacency matrix, adjacency list, Topological sort, dijkstra’s algorithm, prim’s algorithm,
Kruskal’s algorithm, biconnectivity, articulation points, Depth first search, breadth first search
and strong component.
225
Chapter 11- Graphs
Big Questions
1.Explainthevarious representationofgraphwithexamplein detail?
2.Define topological sort? Find a topological ordering for the following graph.
3. Explain Dijkstra's algorithm and find the shortest path from A to all other vertices for the
following graph.
226
Chapter 11- Graphs
4.ExplainPrim's algorithmand find the minimum spanning tree for the graph.
5. Explain Kruskal's algorithm and find the minimum spanning tree for the above graph.
6. Find all the articulation points for the following graph.
227