Upload
others
View
6
Download
0
Embed Size (px)
Citation preview
UNIT-4
Graph: Terminology, Representation, Traversals – Applications - spanning trees, shortest path
and Transitive closure, Topological sort. Sets: Representation - Operations on sets –
Applications.
1. Name the different ways of representing a graph?
a.Adjacencymatrix
b. Adjacency list
2. What is an undirected acyclic graph?
When every edge in an acyclic graph is undirected, it is called an undirected
acyclic graph. It is also called as undirected forest.
3. What are the two traversal strategies used in traversing a graph?
a.Breadthfirstsearch
b. Depth first search
4. What is a minimum spanning tree?
A minimum spanning tree of an undirected graph G is a tree formed from graph
edges that connects all the vertices of G at the lowest total cost.
5. Name two algorithms two find minimum spanning tree Kruskal’salgorithm
Prim’s algorithm
6. Define graph traversals.
Traversing a graph is an efficient way to visit each vertex and edge exactly once.
7. List the two important key points of depth first search.
i) If path exists from one node to another node, walk across the edge – exploring
the edge.
ii) If path does not exist from one specific node to any other node, return to the
previous node where we have been before – backtracking.
8. What do you mean by breadth first search (BFS)?
BFS performs simultaneous explorations starting from a common point and
spreading out independently.
9.Differentiate BFS and DFS.
No. DFS BFS
1. Backtracking is possible from a
dead end
Backtracking is not possible
2. Vertices from which exploration is
incomplete are processed in a
LIFO order
The vertices to be explored are
organized as a
FIFO queue
3. Search is done in one particular
direction
The vertices in the same level are
maintained
parallely
10. What is meant by topological sort?
Topological Sort. A cycle in a diagraph or directed graph G is a set of edges, {(v1, v2),
(v2, v3), ..., (vr −1, vr)} where v1 = vr. A diagraph is acyclic if it has no cycles. Such a graph is
often referred to as a directed acyclic graph, or DAG, for short.
11 Marks
GRAPH – INTRODUCTION
Graph is a non-linear data structure.
Graphs can be used anywhere in the real world.
Eg. Airlines : Cities are connected through airlines. This can be represented through
graph structure which includes cities as nodes and airlines by edges.
GRAPH TERMINOLOGIES
UNDIRECTED GRAPH:
An undirected graph is that in which, the pair of vertices representing the edges is unordered.
DIRECTED GRAPH:
An directed graph is that in which, each edge is an ordered pair of vertices, (i.e.) each
edge is represented by a directed pair. It is also referred to as digraph.
COMPLETE GRAPH:
An n vertex undirected graph with exactly n(n-1)/2 edges is said to be complete graph.
The graph G is said to be complete graph .
SUBGRAPH:
A sub-graph of G is a graph G ‘ such that V(G’) V(G ) and E(G ‘) E(G). some of the sub-
graphs are as follow,
(a) (b)
© (d)
FIG: Graph G FIG: Subgraphs of G
ADJACENT VERTICES:
`A vertex v1 is said to be a adjacent vertex if there exist an edge (v1,v2) or (v2,v1).
PATH:
A path from vertex V to the vertex W is a sequence of vertices, each adjacent to the next.
The length of the graph is the number of edges in it.
CONNECTED GRAPH:
A graph is said to be connected if there exist a path from any vertex to another vertex.
UNCONNECTED GRAPH:
A graph is said as unconnected graph if there exist any 2 unconnected components.
1
2 3
4
1
2 3
4
1
2 3
4
1
2 3
FIG: Unconnected Graph
STRONGLY CONNECTED GRAPH:
A digraph is said to be strongly connected if there is a directed path from any vertex to any other
vertex.
WEAKLY CONNECTED GRAPH:
If there dos not exist a directed path from one vertex to another vertex then it is said to be a
weakly connected graph.
1
3
1 4
1
2
5
1
6
1
8 7
1
1
2
3
5 4
1
2
3
5 4
CYCLE
A cycle is a path in which the first and the last vertices are the same.
Eg. 1,3,4,7,2,1
DEGREE:
The number of edges incident on a vertex determines its degree. There are two types of degrees
In-degree and out-degree.
IN-DEGREE of the vertex V is the number of edges for which vertex V is a head and OUT-
DEGREE is the number of edges for which vertex is a tail.
WEIGHTED GRAPH:
A graph (or digraph) is termed as weighted graph if all edges in it are labeled with some
weights. Eg:
SELF LOOP :
If there is an edge whose starting and end vertices are same, that is, (vi, vj) is an edge,
then it is called a self loop.
ACYCLIC GRAPH :
If there is a path containing one or more edges which starts from a vertex vi and
terminates into the same vertex then the path is known as a cycle. If a graph(digraph) does not
have any cycle then it is called acyclic graph.
GRAPH REPRESENTATION
How to represent a graph? (3 Marks April 2015)
The graphs can be represented by the follow three methods:
1. Adjacency matrix.
2. Adjacency list.
ADJACENCY MATRIX:
The adjacency matrix A for a graph G = (V,E) with n vertices, is an n* n matrix of bits ,such
that A
Ij = 1 , if there is an edge from vi to vj and
Aij = 0, if there is no such edge.
The adjacency matrix for the graph G is,
1 0 1 1 1
2 1 0 1 1
3 1 1 0 1
4 1 1 1 0
1
2 3
4
The space required to represent a graph using its adjacency matrix is n* n bits. About half this
space can be saved in the case of an undirected graphs by storing only the upper or lower
triangle of the matrix. From the adjacency matrix , one may readily determine if there an edge
connecting any two vertices I and j. for an undirected graph the degree of any vertices I is its
row ∑ n (j=1) A(I, j). For a directed graph the row is the out-degree and column sum is the in-
degree.
The adjacency matrix is a simple way to represent a graph , but it has 2 disadvantages,
1. it takes O(n*n) space to represent a graph with n vertices ; even for sparse graphs and
2. it takes…(n*n) times to solve most of the graph problems.
ADJACENCY LIST:
In the representation of the n rows of the adjacency matrix are represented as n linked
lists. There is one list for each vertex in G. the nodes in list I represent the vertices that are
adjacent from vertex i. Each nodes has at least 2 fields: VERTEX and LINK. The VERTEX
fields contain the indices of the vertices adjacent to vertex i. In the case of an undirected graph
with n vertices and e edges ,this representation requires n head nodes and 2e list nodes.
Vertex 1
Vertex 2
Vertex 3
Vertex 4
The degree of the vertex in an undirected graph may be determined by just counting the number
of nodes in its adjacency list. The total number of edges in G may , therefore be determined in
time O(n+e).in the case of digraph the number of list nodes is only e. the out-degree of any
vertex can be determined by counting the number of nodes in an adjacency list. The total
number of edges in G can, therefore be determined in O(n+e).
GRAPH TRAVERSALS
Discuss about Graph Traversals. (6 Marks April 2013)
There are two graph traversal methods.
2 3 4 0
1 3 4 0
1 2 4 0
1 2 3 0
Depth First search
Breadth First Search
DEPTH-FIRST SEARCH (DFS)
1. Starting at some vertex, v, we process v and then recursively traverse all vertices adjacent to
v. To do this, when a vertex v is visited, we mark it visited, since now we have been there,
and recursively call depth-first search on all adjacent vertices that are not already marked.
2. We implicitly assume that for undirected graphs every edge (v, w) appears twice in the
adjacency lists: once as (v, w) and once as (w, v).
3. The (global) boolean array visited[ ] is initialized to FALSE.
4. By recursively calling the procedures only on nodes that have not been visited, we guarantee
that we do not loop indefinitely.
5. If the graph is undirected and not connected, or directed and not strongly connected, this
strategy might fail to visit some nodes.
6. We then search for an unmarked node, apply a depth-first traversal there, and continue this
process until there are no unmarked nodes.
7. Because this strategy guarantees that each edge is encountered only once, the total time to
perform the traversal is O(|E| + |V|), as long as adjacency lists are used.
void dfs( vertex v )
{
visited[v] = TRUE;
for each w adjacent to v
if( !visited[w] )
dfs( w );
}
Undirected Graphs
1. An undirected graph is connected if and only if a depth-first search starting from any node
visits every node.
2.Because this test is so easy to apply, assume that the graphs we deal with are connected. If they
are not, then find all the connected components and apply our algorithm on each of these in
turn.
Complexity analysis
Assume that graph is connected. Depth-first search visits every vertex in the graph and
checks every edge its edge. Therefore, DFS complexity is O(V + E). As it was mentioned before,
if an adjacency matrix is used for a graph representation, then all edges, adjacent to a vertex can't
be found efficiently, that results in O(V2) complexity.
BREADTH FIRST SEARCH (BFS)
1. Assume a particular node has been designated as starting point
2. Let A be the last node Visitor and A has A neighbor N1, N2 until Nk.
3. A Breadth First Search will
Visit N1 then N2 and so forth through Nk.
Proceed to traverse all the unvisited neighbours of N1 then
Traverse the immediate neighbor of N2……Nk in a similar fashion.
Breadth First Search algorithm used in
Prim's MST algorithm.
Dijkstra's single source shortest path algorithm.
Like depth first search, BFS traverse a connected component of a given graph and defines a
spanning tree.
Algorithm Breadth First Search
1. BFS starts at a given vertex, which is at level 0. In the first stage, we visit all vertices at
level 1.
2. In the second stage, we visit all vertices at second level. These new vertices, which are
adjacent to level 1 vertices, and so on.
3. The BFS traversal terminates when every vertex has been visited.
Algorithm
visited [s]=1
queue [++ rear]=s
display(s);
while (front<=rear)
{
breadthfirst (queue [front]);
front++;
}
breathfirst(queue(vertex)
{
for(i=1;i<=n;i++)
{
if(graph[vertex][i]==1)
{
if(visited[i]==0)
{
visited [i]=1;
display( i);
queue [++rear]=i;
}
}
}
BFS labels each vertex by the length of a shortest path (in terms of number of edges)
from the start vertex.
Example
As with the depth first search (DFS), the discovery edges form a spanning tree, which in
this case we call the BSF-tree.
BSF used to solve following problem
Testing whether graph is connected.
Computing a spanning forest of graph.
Computing, for every vertex in graph, a path with the minimum number of edges between
start vertex and current vertex or reporting that no such path exists.
Computing a cycle in graph or reporting that no such cycle exists.
Analysis
Total running time of BFS is O(V + E).
APPLICATIONS OF GRAPHS
The applications of a Graph include the following
Finding Minimum Spanning Trees (MST) – Prim’s and Kruskal’s Algorithm
Finding shortest path - Dijkstra’s Algorithm
Transitive closure – Warshall’s Algorithm
Topological sort.
Minimum Spanning Tree (MST)
Write short notes on Minimal cost Algorithm. (6 Marks April 2012)
What is spanning tree? Explain. (4 Marks April 2015)
Spanning tree
1. It is a subset of a tree in which all vertices of tree are present, but it may not contain all
edges. A graph can have mo re than one spanning tree.
2. Suppose we have a connected undirected graph, then a spanning tree of the graph is a
connected sub graph in which there are no cycles.
3. MST of a weighted connected graph G is its spanning tree with smallest weight, where
the weight of a tree is defined as the sum of the weights on all its edges.
4. The total no. of edges the MST is |V| -1, where v is the no. of vertices.
5. A MST exists iff G is connected.
6. For any spanning tree T, if an edge e (that is ) not in T is added, a cycle is created.
7. The removal of any edge on the cycle reinstates the spanning tree property.
Methods to compute MST
1. Prim’s algorithm
2. Kruskal’s algorithm
Prim’s algorithm
1. It is one of the ways to compute MST. It uses a greedy technique. This algorithm
begins with a set U initialized to {1}.
2. It then grows a spanning tree, cons idering one edge at a time.
3. At each step, it finds the shortest edges (u, v) such that the cost of (u, v) is the smallest
among all edges, where u is in MST and V is not in MST.
Steps
Create a queue of size equal to the number of vertices in the graph given.
Empty the queue created using makeempty().
Insert the source vertex into the queue.
The queue is not empty. Dequeue the vertex at the front of the queue and store it in v.
For each w adjacent to v, check whether the cost is ∞.
If the cost is ∞ calculate the cost, cost(w)=cost(v,w).Include v in the path of w.
If the cost is already present, calculate the new cost. If the new cost is less than the old
one, update. Update the path also. Else ignore.
Enqueue w(the adjacent vertex of v)with the smallest cost.
Calculate the total cost of the minimum spanning tee by adding the cost on the edges of
the tree.
For ‘n’ vertices, there will be ‘n-1’ edges.
Total Running Time=(|E|+|V|2) = O(|V|2).
Procedure for prim`s algorithm
void prims (graph G)
{
Queue Q;
vertex v, w;
Q=create Queue (numvertex);
make empty (Q);
enqueue (S, Q);
while (! is empty (Q))
{
v=Dequeue (Q);
for each unvisited w adjacent to v
{
if (cost (w) = = ∞)
{
cost (w) =cost (v, w);
path (w) =v;
}
else
{
cost1 (w) =cost (v, w);
if (cost1 (w) <cost (w) ;
{
cost (w) =cost1 (w);
path (w) =v;
}
}
enqueue (w with the minimum cost);
}
}
}
Example
a (-,-) b (a,2) c(a,4) d(a,1) e(-,∞) f (-,∞) g(-,∞)
d (a,1) b (a,2) c(d,2) e(d,7) f(d,8) g(d,4)
b (a,2) c (d,2) e(d,7) f(d,8) g(d,4)
c (d,2) e (d,7) f(c,5) g(d,4)
g (d,4) e (g,6) f(g,1)
f (g,1) e (g,6)
e (g,6) Empty
Total cost of the minimum spanning tree = 16.
KRUSKAL’S ALGORITHM
It also finds the minimum spanning tree like the Prim’s algorithm.
1. Pair of vertices with minimum weight is to be chosen.
2. Each time the edge with minimum weight has to be selected.
3. It is not necessary that edges with minimum weight should be adjacent.
4. Cycle should not be formed.
Algorithm
T= empty spanning tree
E= set of edges
N= no. of nodes in graph
while T has fewer than N – 1 edges
{
remove an edge (V, W) of lowest cost from E
if adding (V, W) to T would create a cycle
then discard (V, W)
else add (V, W)
}
Steps
List the edges in order of increasing edge costs.
Choose an edge with the lowest cost. Add it to the tree.
Keep adding the edges, making sure that a cycle is not formed at any instant.
On adding an edge if a cycle is formed, then the edge has to be rejected.
Choose the next edge from the list.
Once all the vertices are connected, then the process can be stopped.
Calculate the total cost of the minimum spanning tee by adding the cost on the edges of
the tree.
For ‘n’ vertices, there will be ‘n-1’ edges.
Example
Total cost of the minimum spanning tree= 16.
Edges Cost /
Weight
Action
(a,d) 1 Accepted
(f,g) 1 Accepted
(a,b) 2 Accepted
(c,d) 2 Accepted
(b,d) 3 Rejected
(a,c) 4 Rejected
(d,g) 4 Accepted
(c,f) 5 Rejected
(e,g) 6 Accepted
(d,e) 7 Rejected
Edges Cost/
Weight
(a,d) 1
(f,g) 1
(a,b) 2
(c,d) 2
(b,d) 3
(a,c) 4
(d,g) 4
(c,f) 5
(e,g) 6
(d,e) 7
SHORTEST PATH ALGORITHMS
1. The shortest path algorithm determines the minimum cost of the path from source to
every other vertex.
N-1
2. The cost of the path v1, v2, vn is ∑ C i,i+1. This is referred to as weighted path length.
i=1
3. The unweighted path length is merely the no. of edges on the path namely, N-1.
4. There are 2 algorithms that determine the shortest paths.
SHORTEST PATH
Dijkstra’s algorithm – Determines the Single –Source Shortest Path
Floyd’s algorithm – Determines the All – Pairs Shortest Path
Discuss about the shortest path algorithms. Illustrate it with example. (11 Marks April
2013)
Dijkstra`s algorithm (single –source shortest path algorithm)
Explain the Dijikstra’s algorithm to find the shortest path for the following graph. Also
develop an algorithm for the same. (11 Marks Nov 2010),(11 Marks April 2015)
Write and explain Dijikstra’s algorithm to finding the shortest path. (11 Marks April 2012)
Explain the Dijistra shortest path Algorithm with example.(11 Marks Nov 2013)
1. Dijkstra’s algorithm is the general method to solve the single source shortest path
problem.
2. This is applied to the weighted graph G.
3. Dijkstra`s algoritm is the prime example of greedy technique which generally solves a
problem in stages by doing what appears to be the best thing at each stage.
4. This algorithm proceeds in stages just like the weighted shortest path algorithm.
5. For a given source vertex in the graph the algorithm finds the shortest path from the
source vertex to every other vertex.
6. It can also be used for finding costs of shortest path from a single vertex to a single
destination vertex by stopping the algorithm once the shortest route to the destination
vertex has been determined.
Steps
Create a queue of size equal to the number of vertices in the graph given.
Empty the queue created using makeempty().
Insert the source vertex into the queue.
The queue is not empty. Dequeue the vertex at the front of the queue and store it in V.
For each w adjacent to v, check whether the distance is ∞.
If the distance is ∞ calculate the distance, dist(w)=dist(v)+dist(v,w). Include v in the path
of w.
If the distance is already present, calculate the new distance. If the new distance is less
than the old one, update. Update the path also. Else ignore.
Enqueue w(the adjacent vertex of v)with the shortest distance.
Total Running Time=(|E|+|V|2) = O(|V|2).
PROCEDURE FOR DIJKSTRA’S ALGORITHM
void dijkstra (graph G)
{
Queue Q;
vertex v, w;
Q=create Queue (numvertex);
make empty (Q);
enqueue (S, Q);
while (!isempty (Q))
{
v=Dequeue (Q);
for each unvisited w adjacent to v
{
if (dist (w) = = ∞)
{
dist (w) =dist (v) +dist (v, w);
path (w) =v;
}
else
{
dist1 (w) =dist (v) +dist (v, w);
if (dist1 (w) <dist (w);
{
dist (w) =dist1 (w);
path (w) =v;
}
}
enqueue (w with the shortest distance);
}
}
}
Example
COST PATH POOL OF UNVISITED VERTICES AND THEIR COSTS
FROM THE SOURCE
a=0 a (-,0) b (a,2) c(-,∞) d(a,1) e(-,∞) f(-,∞) g(-,∞0
d=1 d(a,1) b (a,2) c(d,3) e(d,3) f(d,9) g(d,5)
b=2 b(a,2) c (d,3) e (d,3) f (d,9) g(d,5)
c=3 c(d,3) e (d,3) f(c,8) g(d,5)
e=3 e(d,3) f (c,8) g(d,5)
g=5 g(d,5) f (g,6)
f=6 f(g,6) Empty.
SOURCE AND
DESTINATION COST
a to a 0
a to b 2
a to c 3
a to d 1
a to e 3
a to f 6
a to g 5
TOPOLOGICAL SORTING
Explain the topological with an example. (11 Marks April 2014)
Toplological sorting is an ordering of vertices of a graph, such that if there is a path u to v in the
graph then u appears before v in the ordering.
Topological ordering is not possible if the graph has a cycle, since for two vertices u and v on the
cycle, u precedes v and v precedes u. For a directed acyclic graph, there exists a topological ordering of
vertices.
A simple algorithm to find a topological ordering is to find out any vertex with indegree zero, i.e,
a vertex without any predecessor. We can add this vertex in an ordering set (initially which is empty) and
remove it along with its edge(s) from the graph. Thus, we can repeat the same stratergy on the remaining
graph until it is empty.
Example:
TOPOLOGICAL SORT ALGORITHM: