Unit 3
Unit 3
Unit 3
UNIT-3
GRAPH
DEFINING GRAPH:
A graphs g consists of a set V of vertices (nodes) and a set E of edges (arcs). We write
G=(V,E). V is a finite and non-empty set of vertices. E is a set of pair of vertices; these pairs are called as
edges . Therefore,
V(G).read as V of G, is a set of vertices and E(G),read as E of G is a set of edges.
An edge e=(v, w) is a pair of vertices v and w, and to be incident with v and w.
2 3
FIG: Graph G
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.
DIRECTED GRAPH
COMPLETE GRAPH:
B.Balakonda Reddy KKCT Page 1
Design and Analysis of Algorithms Computer Science and Engg.
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 .
In Breadth first search we start at vertex v and mark it as having been reached. The vertex v at this
time is said to be unexplored. A vertex is said to have been explored by an algorithm when the algorithm
has visited all vertices adjacent from it. All unvisited vertices adjacent from v are visited next. There are
new unexplored vertices. Vertex v has now been explored. The newly visited vertices have not been
explored and are put onto the end of the list of unexplored vertices. The first vertex on this list is the next
to be explored. Exploration continues until no unexplored vertex is left. The list of unexplored vertices
acts as a queue and can be represented using any of the standard queue representations.
In Breadth First Search we start at a vertex ‘v’ and mark it as having been reached (visited).
The vertex ‘v’ is at this time said to be unexplored.
A vertex is said to have been explored by an algorithm when the algorithm has visited all vertices
adjust from it.
All unvisited vertices adjust from ‘v’ are visited next. These are new unexplored vertices.
Vertex ‘v’ has now been explored. The newly visit vertices have not been explored and are put on
the end of a list of unexplored vertices.
The first vertex on this list in the next to be explored. Exploration continues until no unexplored
vertex is left.
The list of unexplored vertices operates as a queue and can be represented using any of the start
queue representation.
ALGORITHM:
for i= 1 to n do
visited[i] =0;
for i =1 to n do
if (visited[i]=0)then BFS(i)
}
here the time and space required by BFT on an n-vertex e-edge graph one O(n+e) and O(n) resp if
adjacency list is used.if adjancey matrix is used then the bounds are O(n2) and O(n) resp
A depth first search of a graph differs from a breadth first search in that the exploration of a vertex
v is suspended as soon as a new vertex is reached. At this time the exploration of the new vertex u begins.
When this new vertex has been explored, the exploration of u continues. The search terminates when all
reached vertices have been fully explored. This search process is best-described recursively.
Algorithm DFS(v)
{
visited[v]=1
for each vertex w adjacent from v do
{
If (visited[w]=0)then
DFS(w);
}
}
Backtracking:
BACKTRACKING
Many problems which deal with searching for a set of solutions or for a optimal solution satisfying
some constraints can be solved using the backtracking formulation.
To apply backtracking method, tne desired solution must be expressible as an n-tuple (x1…xn)
where xi is chosen from some finite set Si.
The problem is to find a vector, which maximizes or minimizes a criterion function P(x1….xn).
The major advantage of this method is, once we know that a partial vector (x1,…xi) will not lead
to an optimal solution that (mi+1………..mn) possible test vectors may be ignored entirely.
Many problems solved using backtracking require that all the solutions satisfy a complex set of
constraints.
i) Explicit constraints.
ii) Implicit constraints.
1) Explicit constraints:
Explicit constraints are rules that restrict each Xi to take values only from a given set.
Some examples are,
Xi 0 or Si = {all non-negative real nos.}
Xi =0 or 1 or Si={0,1}.
Li Xi Ui or Si= {a: Li a Ui}
All tupules that satisfy the explicit constraint define a possible solution space for I.
2) Implicit constraints:
The implicit constraint determines which of the tuples in the solution space I can actually
satisfy the criterion functions.
Algorithm:
B.Balakonda Reddy KKCT Page 4
Design and Analysis of Algorithms Computer Science and Engg.
All solutions are generated in X[1:n] and printed as soon as they are determined.
T(X[1]…..X[k-1]) is all possible values of X[k] gives that X[1],……..X[k-1] have already been
chosen.
Bk(X[1]………X[k]) is a boundary function which determines the elements of X[k] which satisfies
the implicit constraint.
1. Sum of subsets.
2. Graph coloring.
3. Hamiltonian cycle.
4. N-Queens problem.
SUM OF SUBSETS:
We are given ‘n’ positive numbers called weights and we have to find all combinations of these
numbers whose sum is M. this is called sum of subsets problem.
If we consider backtracking procedure using fixed tuple strategy , the elements X(i) of the solution
vector is either 1 or 0 depending on if the weight W(i) is included or not.
If the state space tree of the solution, for a node at level I, the left child corresponds to X(i)=1 and
right to X(i)=0.
Example:
B.Balakonda Reddy KKCT Page 5
Design and Analysis of Algorithms Computer Science and Engg.
In state space tree of the solution the rectangular node lists the values of s, k, r, where s is the sum
of subsets,’k’ is the iteration and ‘r’ is the sum of elements after ‘k’ in the original set.
S, n, r
0,1,73
X(1)=1 x(1)=0
5,2,68 0,2,68
X(4)=1 x(4)=0
X(4)=0
15,5,33 B 5,5,33 10,5,33
X(5)=1 x(5)=1
A 20,6,18
In the state space tree, edges from level ‘i’ nodes to ‘i+1’ nodes are labeled with the values of Xi,
which is either 0 or 1.
The left sub tree of the root defines all subsets containing Wi.
The right subtree of the root defines all subsets, which does not include Wi.
Assign X(k)<- 1.
If S+X(k)=M then we print the subset b’coz the sum is the required output.
If the above condition is not satisfied then we have to check S+X(k)+W(k+1)<=M. If so, we have
to generate the left sub tree. It means W(t) can be included so the sum will be incremented and we
have to check for the next k.
After generating the left sub tree we have to generate the right sub tree, for this we have to check
S+W(k+1)<=M.B’coz W(k) is omitted and W(k+1) has to be selected.
Repeat the process and find all the possible combinations of the subset.
Algorithm:
Algorithm sumofsubset(s,k,r)
{
//generate the left child. note s+w(k)<=M since Bk-1 is true.
X{k]=1;
If (S+W[k]=m) then write(X[1:k]); // there is no recursive call here as W[j]>0,1<=j<=n.
Else if (S+W[k]+W[k+1]<=m) then sum of sub (S+W[k], k+1,r- W[k]);
//generate right child and evaluate Bk.
If ((S+ r- W[k]>=m)and(S+ W[k+1]<=m)) then
{
X{k]=0;
sum of sub (S, k+1, r- W[k]);
}
}
HAMILTONIAN CYCLES:
Let G=(V,E) be a connected graph with ‘n’ vertices. A HAMILTONIAN CYCLE is a round trip
path along ‘n’ edges of G which every vertex once and returns to its starting position.
If the Hamiltonian cycle begins at some vertex V1 belongs to G and the vertex are visited in the
order of V1,V2…….Vn+1,then the edges are in E,1<=I<=n and the Vi are distinct except V1 and
Vn+1 which are equal.
1 2 3 4
8 7 6 5
->1,3,4,5,6,7,8,2,1 and
->1,2,8,7,6,5,4,3,1.
The backtracking algorithm helps to find Hamiltonian cycle for any type of graph.
Procedure:
1. Define a solution vector X(Xi……..Xn) where Xi represents the I th visited vertex of the proposed
cycle.
3. The solution array initialized to all zeros except X(1)=1,b’coz the cycle should start at vertex ‘1’.
6. When these two conditions are satisfied the current vertex is included in the cycle, else the next
vertex is tried.
7. When the nth vertex is visited we have to check, is there any path from nth vertex to first 8vertex.
if no path, the go back one step and after the previous visited node.
}
Repeat
}
8-QUEENS PROBLEM:
This 8 queens problem is to place n-queens in an ‘N*N’ matrix in such a way that no two queens
attack each otherwise no two queens should be in the same row, column, diagonal.
Solution:
th
The solution vector X (X1…Xn) represents a solution in which Xi is the column of the row
where I th queen is placed.
The function, which is used to check these two conditions, is [I, X (j)], which gives position of the
I th queen, where I represents the row and X (j) represents the column position.
Consider two dimensional array A[1:n,1:n] in which we observe that every element on the same
diagonal that runs from upper left to lower right has the same value.
Also, every element on the same diagonal that runs from lower right to upper left has the same
value.
Suppose two queens are in same position (i,j) and (k,l) then two queens lie on the same diagonal ,
if and only if |j-l|=|I-k|.
Initialize x array to zero and start by placing the first queen in k=1 in the first row.
To find the column position start from value 1 to n, where ‘n’ is the no. Of columns or no. Of
queens.
If k=1 then x (k)=1.so (k,x(k)) will give the position of the k th queen. Here we have to check
whether there is any queen in the same column or diagonal.
For this considers the previous position, which had already, been found out. Check whether
X (I)=X(k) for column |X(i)-X(k)|=(I-k) for the same diagonal.
If any one of the conditions is true then return false indicating that k th queen can’t be placed in
position X (k).
For not possible condition increment X (k) value by one and precede d until the position is found.
If the position X (k) n and k=n then the solution is generated completely.
If k<n, then increment the ‘k’ value and find position of the next queen.
If the position X (k)>n then k th queen cannot be placed as the size of the matrix is ‘N*N’.
So decrement the ‘k’ value by one i.e. we have to back track and after the position of the previous
queen.
Algorithm:
Algorithm place (k,I)
//return true if a queen can be placed in k th row and I th column. otherwise it returns //
//false .X[] is a global array whose first k-1 values have been set. Abs® returns the //absolute value of r.
{
For j=1 to k-1 do
If ((X [j]=I) //two in same column.
Or (abs (X [j]-I)=Abs (j-k)))
Example: 4 queens.
Two possible solutions are
Q Q
Q Q
Q Q
Q Q
Solutin-1 Solution 2
(2 4 1 3) (3 1 4 2)
GRAPH COLORING:
Let ‘G’ be a graph and ‘m’ be a given positive integer. If the nodes of ‘G’ can be colored in such a
way that no two adjacent nodes have the same color. Yet only ‘M’ colors are used. So it’s called
M-color ability decision problem.
The graph G can be colored using the smallest integer ‘m’. This integer is referred to as chromatic
number of the graph.
A graph is said to be planar iff it can be drawn on plane in such a way that no two edges cross each
other.
Suppose we are given a map then, we have to convert it into planar. Consider each and every
region as a node. If two regions are adjacent then the corresponding nodes are joined by an edge.
4 5
2
1
3
1 is adjacent to 2, 3, 4.
2 is adjacent to 1, 3, 4, 5
3 is adjacent to 1, 2, 4
4 is adjacent to 1, 2, 3, 5
5 is adjacent to 2, 4
2 3
5 4
A
Steps to color the Graph:
l
g
First create the adjacency
o matrix graph(1:m,1:n) for a graph, if there is an edge between i,j then
C(i,j) = 1 otherwise
r C(i,j) =0.
i
The Colors willt be represented by the integers 1,2,…..m and the solutions will be stored in the
array X(1),X(2),………..,X(n)
h ,X(index) is the color, index is the node.
m
He formula is used to set the color is,
X(k) = (X(k)+1)
m % (m+1)
C
First one chromatico number is assigned ,after assigning a number for ‘k’ node, we have to check
whether the adjacent
l nodes has got the same values if so then we have to assign the next value.
o
Repeat the procedure
r until all possible combinations of colors are found.
i
B.Balakonda Reddy n KKCT Page 12
g
(
k
)
/
Design and Analysis of Algorithms Computer Science and Engg.
The function which is used to check the adjacent nodes and same color is,
If(( Graph (k,j) == 1) and X(k) = X(j))
Example:
1 2
4 3
N= 4
M= 3
Adjacency Matrix:
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
The state space tree will give all possible colors in that ,the numbers which are inside the circles are
nodes ,and the branch with a number is the colors of the nodes.
Algorithm:
Algorithm mColoring(k)
// the graph is represented by its Boolean adjacency matrix G[1:n,1:n] .All assignments //of 1,2,
……….,m to the vertices of the graph such that adjacent vertices are assigned //distinct integers are
printed. ’k’ is the index of the next vertex to color.
{
repeat
{
// generate all legal assignment for X[k].
Nextvalue(k); // Assign to X[k] a legal color.
If (X[k]=0) then return; // No new color possible.
If (k=n) then // Almost ‘m’ colors have been used to color the ‘n’ vertices
Write(x[1:n]);
Else mcoloring(k+1);
}until(false);
}
Algorithm Nextvalue(k)
// X[1],……X[k-1] have been assigned integer values in the range[1,m] such that //adjacent values have
distinct integers. A value for X[k] is determined in the //range[0,m].X[k] is assigned the next highest
numbers color while maintaining //distinctness form the adjacent vertices of vertex K. If no such color
exists, then X[k] is 0.
{
repeat
{
X[k] = (X[k]+1)mod(m+1); // next highest color.
If(X[k]=0) then return; //All colors have been used.
For j=1 to n do
{
// Check if this color is distinct from adjacent color.
If((G[k,j] 0)and(X[k] = X[j]))
// If (k,j) is an edge and if adjacent vertices have the same color.
Then break;
}
The problem is similar to the zero-one (0/1) knapsack optimization problem is dynamic
programming algorithm.
We are given ‘n’ positive weights Wi and ’n’ positive profits Pi, and a positive number ‘m’ that is
the knapsack capacity, the is problem calls for choosing a subset of the weights such that,
m and is Maximized.
The Solution space is the same as that for the sum of subset’s problem.
Bounding functions are needed to help kill some live nodes without expanding them. A good
bounding function for this problem is obtained by using an upper bound on the value of the best
feasible solution obtainable by expanding the given live node.
The profits and weights are assigned in descending order depend upon the ratio.
Solution :
After assigning the profit and weights ,we have to take the first object weights and check if the
first weight is less than or equal to the capacity, if so then we include that object (i.e.) the unit is 1.
(i.e.) K 1.
Then We are going to the next object, if the object weight is exceeded that object does not fit. So
unit of that object is ‘0’.(i.e.) K=0.
Then We are going to the bounding function ,this function determines an upper bound on the best
solution obtainable at level K+1.
Algorithm:
Algorithm Bknap(k,cp,cw)
// ‘m’ is the size of the knapsack; ‘n’ no.of weights & profits. W[]&P[] are the //weights & weights.
P[I]/W[I] P[I+1]/W[I+1].
//fwFinal weights of knapsack.
//fp final max.profit.
//x[k] = 0 if W[k] is not the knapsack,else X[k]=1.
{
// Generate left child.
If((W+W[k] m) then
{
Y[k] =1;
If(k<n) then Bnap(k+1,cp+P[k],Cw +W[k])
If((Cp + p[w] > fp) and (k=n)) then
{
fp = cp + P[k];
fw = Cw+W[k];
for j=1 to k do X[j] = Y[j];
}
}
Algorithm Bound(cp,cw,k)
// cp current profit total.
//cw current weight total.
//kthe index of the last removed item.
//mthe knapsack size.
{
b=cp;
c=cw;
for I =- k+1 to n do
{
c= c+w[I];
if (c<m) then b=b+p[I];
else return b+ (1-(c-m)/W[I]) * P[I];
}
return b;
}
Example:
M= 6 Wi = 2,3,4 4 2 2
Xi = 1 0 1
The maximum weight is 6
Fp = (-1)
1 3 & 0+4 6
cw = 4,cp = 5,y(1) =1
k = k+2
2 3 but 7>6
so y(2) = 0
So bound(5,4,2,6)
B=5
C=4
I=3 to 3
C=6
6 6
So return 5+(1-(6-6))/(2*1)
K=4.
If 4> 3 then
Fp =6,fw=6,k=3 ,x(1) 1 0 1
The solution Xi 1 0 1
Profit 6
Weight 6.