0% found this document useful (0 votes)
2K views13 pages

Multistage Backward

The algorithm finds all subsets of a set of integers whose sum equals a target sum. It uses backtracking to recursively try all possible combinations, including or excluding each element. It tracks the current sum and included elements. If the sum equals the target, a solution is found and printed. It recursively explores both including and excluding the next element if promising.

Uploaded by

Rama Sugavanam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views13 pages

Multistage Backward

The algorithm finds all subsets of a set of integers whose sum equals a target sum. It uses backtracking to recursively try all possible combinations, including or excluding each element. It tracks the current sum and included elements. If the sum equals the target, a solution is found and printed. It recursively explores both including and excluding the next element if promising.

Uploaded by

Rama Sugavanam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Multistage Graph

Aim

To find a shortest path in a multi-stage graph using backward approach

Description

Multistage graph problem is to determine shortest path from source to destination.A multistage
graph G=(V,E) is a directed graph in which the vertices are partitioned into k>=2 disjoint sets Vi,
1<=i<=k.
Cost ( i, j) = bcost(i,j) = min {bcost(i-1,l) + c(l,j)}
l Vi-1
<l,j> E

Algorithm
Algorithm BGraph(G,k,n,p)
. // Same function as FGraph
{
bcost[1] :=0.0; <r,j>
for j :=2 to n do
{ / / Compute bcost[j].
Let r be such that is an edge of G is an edge of and bcost is an edge of
G and bcost[r] + c[r,j] is minimum;
bcost[j] :=bcost[r] + c[r,j];
d[j] := r;
}
/ / Find a minimum-cost path.
p[1] := 1; p[k] :=n;
for j := k 1 to 2 do p[j] := d[p[j+1]];
}

Steps //Change for backward

1. Maintain a cost matrix cost (n) which stores the distance from any vertex to the
destination.
2. If a vertex is having more than one path, then we have to choose the minimum distance
path and the intermediate vertex, which gives the minimum distance path, will be stored
in the distance array D.
3. In this way we will find out the minimum cost path from each and every vertex.
4. Finally cost(1) will give the shortest distance from source to destination.
5. For finding the path, start from vertex-1 then the distance array D(1) will give the
minimum cost neighbor vertex which in turn give the next nearest vertex and proceed in
this way till we reach the Destination.
6. For a k stage graph, there will be k vertex in the path.
Program

global min,stages,cost,c
n=int(input("Enter no of vertices: "))
stages=int(input("Enter no of stages : "))
stage_vertices=[0 for x in range(n)]

cost=[0 for x in range(n)]


pa=[0 for x in range(n)]
d=[0 for x in range(n)]
c=[[9999 for x in range(n)]for x in range(n)]

def Get_min(s,n):
min_vertex=0
min=9999

for i in range(n):
if(min>(c[s][i]+cost[i])):
print min ,c[s][i],cost[i]
min=c[s][i]+cost[i]
min_vertex=i
return min_vertex

def Forward(n):
global totalcost
totalcost=0
for i in range(n-2,-1,-1):
r=Get_min(i,n)
cost[i]=c[i][r]+cost[r]
totalcost = cost[i]
d[i]=r
pa[0]=0
pa[stages-1]=n-1
for i in range(1,stages):
pa[i]=d[pa[i-1]]

def display( ):
print(" Shortest path is...")
ch=''
for i in range(stages-1):
ch+=str(pa[i]+1)+"--"
ch+=str(n)
print ch
print 'totalcost=', totalcost

for i in range(stages):
print('Enter no of vertices in stage ',i+1)
stage_vertices[i]=int(input(' '))

i=0
j=stage_vertices[0]
k=0
for m in range(stages-1):
for i in range(stage_vertices[m]):
for p in range(stage_vertices[m+1]):
print("Enter cost for " ,k+i+1," to ",j+(p+1),": ")
c[k+i][p+j]=int(input(''))
if c[k+i][p+j]==0:
c[k+i][p+j]=9999
j=j+stage_vertices[m+1]
k=k+stage_vertices[m]

print c
Forward(n)
display( )

Output

Enter no of vertices: 12
Enter no of stages : 5
'Enter no of vertices in stage ', 1
1
'Enter no of vertices in stage ', 2
4
'Enter no of vertices in stage ', 3
3
'Enter no of vertices in stage ', 4
3
'Enter no of vertices in stage ', 5
1
'Enter cost for ', 1, ' to ', 2, ': '
9
'Enter cost for ', 1, ' to ', 3, ': '
7
'Enter cost for ', 1, ' to ', 4, ': '
3
'Enter cost for ', 1, ' to ', 5, ': '
2
'Enter cost for ', 2, ' to ', 6, ': '
4
'Enter cost for ', 2, ' to ', 7, ': '
2
'Enter cost for ', 2, ' to ', 8, ': '
1
'Enter cost for ', 3, ' to ', 6, ': '
2
'Enter cost for ', 3, ' to ', 7, ': '
7
'Enter cost for ', 3, ' to ', 8, ': '
0
'Enter cost for ', 4, ' to ', 6, ': '
0
'Enter cost for ', 4, ' to ', 7, ': '
0
'Enter cost for ', 4, ' to ', 8, ': '
11
'Enter cost for ', 5, ' to ', 6, ': '
0
'Enter cost for ', 5, ' to ', 7, ': '
11
'Enter cost for ', 5, ' to ', 8, ': '
8
'Enter cost for ', 6, ' to ', 9, ': '
6
'Enter cost for ', 6, ' to ', 10, ': '
5
'Enter cost for ', 6, ' to ', 11, ': '
0
'Enter cost for ', 7, ' to ', 9, ': '
4
'Enter cost for ', 7, ' to ', 10, ': '
3
'Enter cost for ', 7, ' to ', 11, ': '
0
'Enter cost for ', 8, ' to ', 9, ': '
0
'Enter cost for ', 8, ' to ', 10, ': '
5
'Enter cost for ', 8, ' to ', 11, ': '
6
'Enter cost for ', 9, ' to ', 12, ': '
4
'Enter cost for ', 10, ' to ', 12, ': '
2
'Enter cost for ', 11, ' to ', 12, ': '
5

cost( 10 12 )= 5
cost( 9 12 )= 2
cost( 8 12 )= 4
cost( 7 12 )= 7
cost( 6 12 )= 5
cost( 5 12 )= 7
cost( 4 12 )= 15
cost( 3 12 )= 18
cost( 2 12 )= 9
cost( 1 12 )= 7
cost( 0 12 )= 16
Shortest path is...
1--2--7--10--12
totalcost= 16

Result:

N queen problem
Ex.No :
Date :
Aim
To place N chess queens on an NN chessboard so that no two queens attack each other.

Description
The N Queen is the problem of placing N chess queens on an NN chessboard so that no two
queens attack each other. The idea is to place queens one by one in different columns, starting
from the leftmost column. When we place a queen in a column, we check for clashes with
already placed queens. In the current column, if we find a row for which there is no clash, we
mark this row and column as part of the solution. If we do not find such a row due to clashes
then we backtrack and return false.
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

{
for j=1 to k-1 do
if ((X [j]=I) Or (abs (X [j]-I)=Abs (j-k))) then
return false;
return true;
}
Algorithm Nqueen (k,n)
//using backtracking it prints all possible positions of n queens in n*n chessboard. So
//that they are non-tracking.
{
for I=1 to n do
{
if place (k,I) then
{
X [k]=I;
if (k=n) then write (X [1:n]);
else nquenns(k+1,n) ;
}
}
}

STEPS
1. Start in the leftmost column
2. If all queens are placed return true.
3. Try all rows in the current column. Do following for every tried row.
a. If the queen can be placed safely in this row then mark this [row, column] as part
of the solution and recursively check if placing queen here leads to a solution.
b. If placing queen in [row, column] leads to a solution then return true.
c. If placing queen doesn't lead to a solution then umark this [row, column]
(Backtrack) and go to step (a) to try other rows.
4. If all rows have been tried and nothing worked, return false to trigger backtracking.

Python Program
board = []
size=input("enter number of queens")
a= [[0 for x in range(size)] for y in range(size)]

def printSolution():
for i in range(size):
print a[i]
return

def danger(row, col):


for (i, j) in board:
if row == i or col == j or abs(row - i) == abs(col - j):
return True
return False

def placequeen(row):
if row > size:
print board
printSolution()
else:
for col in range(1, size + 1):
if not danger(row, col):

board.append((row, col))
a[row-1][col-1]=1
placequeen(row + 1)
board.remove((row,col))
a[row-1][col-1]=0
placequeen(1)

Output
enter number of queens4
[(1, 2), (2, 4), (3, 1), (4, 3)]
[0, 1, 0, 0]
[0, 0, 0, 1]
[1, 0, 0, 0]
[0, 0, 1, 0]

[(1, 3), (2, 1), (3, 4), (4, 2)]


[0, 0, 1, 0]
[1, 0, 0, 0]
[0, 0, 0, 1]
[0, 1, 0, 0]
Sum of subsets
Aim
To find the subset S from S whose sum is equal to sum s

Description
Given a set of positive integers, and a value sum S, find out if there exist a subset in array whose
sum is equal to given sum S
Algorithm:
sumOfSubsets ( i, weightSoFar, totalPossibleLeft )
if (promising ( i )) //may lead to solution
then if ( weightSoFar == S )
then print include[ 1 ] to include[ i ] //found solution
else //expand the node when weightSoFar < S
include [ i + 1 ] = "yes //try including
sumOfSubsets ( i + 1,weightSoFar + w[i + 1],totalPossibleLeft - w[i + 1] )

include [ i + 1 ] = "no //try excluding


sumOfSubsets ( i + 1, weightSoFar , totalPossibleLeft - w[i + 1] )
boolean promising (i )
return ( weightSoFar + totalPossibleLeft S) && ( weightSoFar == S || weightSoFar + w[i
+ 1] S )
Prints all solutions

Algorithm Steps
1. Maintain an array X to represent all elements in the set.
2. The value of Xi indicates whether the weight Wi is included or not.
3. Sum is initialized to 0 i.e., s=0.
4. We have to check starting from the first node.
5. Assign X(k)<- 1.
6. If S+X(k)=M then we print the subset beacause the sum is the required output.
7. 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.
8. 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. Because W(k) is omitted and W(k+1) has to be selected.
9. Repeat the process and find all the possible combinations of the subset.

Python Program
inp = [5,7,10,12,15,18,20 ]
targetSum = 35
numOfElements=len(inp)
set=[0 for x in range(numOfElements)]
selectedElements=[0 for x in range(numOfElements)]
inp.sort()
set=inp

def findSubSets(sumTillNow,index,sumOfRemaining):
selectedElements[index] = 1
if (targetSum == set[index] + sumTillNow):
ch=''
for i in range(numOfElements):
if (selectedElements[i] == 1):
ch=ch+str(set[i])+' '
print ch

if ((index + 1 < numOfElements) and (sumTillNow + set[index] + set[index + 1] <=


targetSum)):
findSubSets(sumTillNow + set[index], index + 1, sumOfRemaining - set[index])
selectedElements[index] = 0

if ((index + 1 < numOfElements) and (sumTillNow + set[index + 1] <= targetSum) and


(sumTillNow + sumOfRemaining - set[index] >= targetSum)):
findSubSets(sumTillNow, index + 1, sumOfRemaining - set[index])

def findSets(set,targetSum):
sumOfAllElements=0
for i in range(numOfElements):
sumOfAllElements = sumOfAllElements+set[i]

findSubSets(0, 0, sumOfAllElements)

findSets(inp, targetSum)

Solution:

5 10 20
5 12 18
7 10 18
15 20
Graph coloring
Aim:

To colour a Graph with m colors using backtracking approach


Description
Given an undirected graph and a number m, determine if the graph can be colored with at most
m colors such that no two adjacent vertices of the graph are colored with same color. Here
coloring of a graph means assignment of colors to all vertices. The idea is to assign colors one by
one to different vertices, starting from the vertex 0. Before assigning a color, we check for safety
by considering already assigned colors to the adjacent vertices. If we find a color assignment
which is safe, we mark the color assignment as part of solution. If we do not a find color due to
clashes then we backtrack and return false.
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;
}
if(j=n+1) then return; //new color found.
} until(false); //otherwise try to find another color.
}

Complexity:

The time spent by Nextvalue to determine the children is (mn)


Total time is = (mn n).
M colors and N vertices

Steps:
1. First create the adjacency matrix graph(1:m,1:n) for a graph, if there is an edge between
i,j then C(i,j) = 1 otherwise C(i,j) =0.
2. The Colors will be represented by the integers 1,2,..m and the solutions will be stored
in the array X(1),X(2),..,X(n) ,X(index) is the color, index is the node.
3. He formula is used to set the color is,
i. X(k) = (X(k)+1) % (m+1)
4. First one chromatic number is assigned ,after assigning a number for k node, we have to
check whether the adjacent nodes has got the same values if so then we have to assign the
next value.
5. Repeat the procedure until all possible combinations of colors are found.
6. The function which is used to check the adjacent nodes and same color is,
a. if(( Graph (k,j) == 1) and X(k) = X(j))
7. Print the solution

Program
def is_safe(n, graph, colors, c):
# Iterate trough adjacent vertices
# and check if the vertex color is different from c
for i in xrange(n):
if graph[n][i] and c == colors[i]: return False
return True

# n = vertex nb
def graphColoringUtil(graph, color_nb, colors, n):
# Check if all vertices are assigned a color
print n, color_nb
if vertex_nb == n:
return True

# Trying differents color for the vertex n


for c in xrange(1, color_nb + 1):
# Check if assignment of color c to n is possible
if is_safe(n, graph, colors, c):
# Assign color c to n
colors[n] = c
# Recursively assign colors to the rest of the vertices
if graphColoringUtil(graph, color_nb, colors, n + 1): return True
# If there is no solution, remove color (BACKTRACK)
colors[n] = 0

# nb of vertex
vertex_nb = 10
# nb of colors
color_nb = 3
# Initiate vertex colors
colors = [0] * vertex_nb

graph = [
[0, 1, 1, 0, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[1, 0, 0, 1, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 1, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 1, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 1, 1, 0]
]
color_name = ["red", "blue", "green","yellow"]
# beginning with vertex 0
if graphColoringUtil(graph, color_nb, colors, 0):
print colors

for i in range(vertex_nb):
print(i, '-', color_name[colors[i] - 1])
else:
print "No solutions"

Output
[1, 2, 2, 1, 2, 3, 1, 3, 3, 1]
(0, '-', 'red')
(1, '-', 'blue')
(2, '-', 'blue')
(3, '-', 'red')
(4, '-', 'blue')
(5, '-', 'green')
(6, '-', 'red')
(7, '-', 'green')
(8, '-', 'green')
(9, '-', 'red')

You might also like