0% found this document useful (0 votes)
87 views30 pages

20CSL57 - Ada Lab - 2018-22

The document provides details about the Analysis and Design of Algorithms lab course for computer science students. It includes 16 experiments covering various algorithm design techniques. Students will implement algorithms like Sieve of Eratosthenes, Merge Sort, Quick Sort, Minimum Spanning Trees, and Shortest Path algorithms. They will be evaluated based on their program implementation, execution and results, as well as viva voce. Continuous assessments and internal tests are used to evaluate students with a total of 25 marks for internal evaluation.

Uploaded by

Ahmad Raza
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)
87 views30 pages

20CSL57 - Ada Lab - 2018-22

The document provides details about the Analysis and Design of Algorithms lab course for computer science students. It includes 16 experiments covering various algorithm design techniques. Students will implement algorithms like Sieve of Eratosthenes, Merge Sort, Quick Sort, Minimum Spanning Trees, and Shortest Path algorithms. They will be evaluated based on their program implementation, execution and results, as well as viva voce. Continuous assessments and internal tests are used to evaluate students with a total of 25 marks for internal evaluation.

Uploaded by

Ahmad Raza
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/ 30

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

LAB MANUAL

ANALYSIS AND DESIGN OF ALGORITHMS LAB


20CSL57

Prepared by Verified by Approved by


Dr Clara kanmani A Dr. Pamela Vinitha Dr. Rajalakshmi
B Dr Rachana P HOD- CSE
ANALYSIS AND DESIGN OF ALGORITHMS LAB

Course Code : 20CSL57 Credits : 02


L: T: P : 0:0:2 CIE Marks: 25
Exam Hours : 3 SEE Marks: 25

Course Outcomes: At the end of the Course, the Student will be able to

20CSL57 Analyze the complexities of various applications in different domains


.1
20CSL57 Implement efficient algorithms to solve problems in various domains
.2
20CSL57 Use suitable design technique to develop efficient algorithms
.3
20CSL57 Compare, implement and understand when to apply various design techniques
.4

Mapping of Course Outcomes to Program Outcomes

P P P P P P P P P PO PO PO
O O O O O O O O O 10 11 12
1 2 3 4 5 6 7 8 9
20CSL57 3 3 3 3 - - - - - 3 - 3
.1
20CSL57 3 3 3 3 2 - 2 - - 3 - 3
.2
20CSL57 3 3 3 3 - - 2 - - 3 - 3
.3
20CSL57 3 3 3 3 2 - - - - 3 - 3
.4

Exp. Experime Hou CO


No nt rs
1 Write a program to find GCD of two numbers using
2 CO1
differential algorithms
2 Write a program to Implement Sieve of Eratosthenes to
2 CO1
generate Prime Numbers Between Given Range
3 Write a program to implement string matching using Brute
2 CO1
force
4 Write a program to implement Merge Sort 3 CO2,
CO3
5 Write a program to implement Quick Sort 3 CO2,
CO3
6 Write a program to obtain minimum cost spanning tree using
3 CO2,
Prim’s Algorithm
CO3
7 Write a program to obtain minimum cost spanning tree using
3 CO2,
Kruskal’s Algorithm
CO3
8 Write a program to obtain shortest path using Djikstra’s
3 CO2,
algorithm
CO3
9 Write a program to compute Binomial Coefficient 3 CO2,
CO3
10 Write a program to obtain shortest path using Floyds
3 CO2,
algorithms
CO3
11 Write a program to compute Transitive closure using
3 CO2,
Warshall’s algorithm
CO3
12 Write a program to implement Breadth First search 3 CO2,
CO3
13 Write a program to implement Depth First search 3 CO2,
CO3
14 Write a program to implement Topological sorting 3 CO2,
CO3
15 Write a program to implement Subset Sum problem using
3 CO4
Backtracking
16 Write a program to implement N Queens problem using
3 CO4
Backtracking

CIE – Continuous Internal Evaluation: LAB (25 Marks

Blooms Taxonomy Tes


ts
Marks (Out of 25) 25
L1: Remember -
L2: Understand -
L3: Apply 10
L4: Analyze 10
L5: Evaluate 5
L6: Create -

SEE – Semester End Examination: Lab (25 Marks)

Blooms Taxonomy Marks (Out of 25)


L1: Remember -
L2: Understand -
L3: Apply 1
0
L4: Analyze 1
0
L5: Evaluate 5
L6: Create -
NEW HORIZON COLLEGE OF ENGINEERING, BANGALORE
Autonomous college permanently affiliated to VTU, Approved by AICTE & UGC
Accredited by NAAC with 'A' grade, Accredited by NBA

DEPARTMENT OF COMPUTER SCIENCE &

ENGINEERING LAB RUBRICS

Course: ANALYSIS AND DESIGN OF ALGORITHMS LAB


Course Code: 20CSL57
Sem: 5

Internal Assessment Marks: 25

Divided into two components:

1. Continuous Assessment: 10 marks


2. Internal Test: 15 marks

1. Continuous Assessment:
i) Will be carried out in every lab (for 12 labs -16 programs)
ii) Each program will be evaluated for 10 marks
iii) Totally for 16 lab programs it will be 160 marks. This will be scaled down to 10.
iv) During the semester, 2 internal tests will be conducted for 25 marks each. The total 50
marks for the internal tests will be scaled down to 15.

Break up of 10 marks (in every lab):

Will be carried out in every lab (for 10 lab programs)

Attributes Descripto Scor


rs es
Complete program with proper variable naming,
3
proper commenting
Complete program with not so proper variable naming,
Program 3
poor commenting
Write-
up(3) Incomplete code 2

Not written 1

Passes all specified test cases efficiently 3


Execution
&
Results Fails in some test cases 2
(3)
Incomplete execution 1

Answers correctly 2

Viva Voce(2) Answers satisfactorily 1

Do not answer any question 0

Record Submits in time and completed (during subsequent lab) 2


completion
and Fails to submit the record in time / incomplete submission 0
submission(2
)

2. Internal Test:
Break up of 25 marks (for each of the 2 internal tests) which is scaled down to 15marks
after the conduction of 2 internal tests:

The 1st lab internal will comprise of the first 5 lab programs and the 2nd lab internal will comprise
of the next 5 lab programs.

Attributes Descriptors Scores


Complete program with proper variable naming,
5
proper commenting
Complete program with not so proper variable naming,
Program Write- 3-4
poor commenting
up (5)
Incomplete code 1-2

Not written 0

Passes all specified test cases efficiently 15


Execution
Fails in some test cases 10-14
& Results
(15)
Incomplete execution 1-9

Answers 100% questions correctly 5

Answers 75% questions correctly 3-4


Viva Voce (5)
Answers satisfactorily 1-2

Does not answer any question 0


SEE Assessment Marks: 25

Session End Examination is conducted for 50 marks which is scaled down to 25 marks.

Attributes Descripto Scor


rs es
Complete program with proper variable naming,
10
proper commenting
Complete program with not so proper variable naming,
Program 8
poor commenting
Write-
up(10) Incomplete code 4

Not written 0

Passes all specified test cases efficiently 30


Execution
Fails in some test cases 20
& Results
(30)
Incomplete execution 10

Answers 100% questions correctly 10

Answers 75% questions correctly 8


Viva Voce(10)
Answers satisfactorily 4

Does not answer any question 0

Lab Course Faculty Course Coordinator


CONTENTS

Exp. List of
No Experiments
1 Write a program to find GCD of two numbers using different algorithms
Write a program to Implement Sieve of Eratosthenes to generate Prime Numbers
2
Between Given Range
3 Write a program to implement string matching using Brute force
4 Write a program to implement Merge Sort
5 Write a program to implement Quick Sort
6 Write a program to obtain minimum cost spanning tree using Prim’s Algorithm
7 Write a program to obtain minimum cost spanning tree using Kruskal’s Algorithm
8 Write a program to obtain shortest path using Djikstra’s algorithm
9 Write a program to compute Binomial Coefficient
10 Write a program to obtain shortest path using Floyds algorithms
11 Write a program to compute Transitive closure using Warshall’s algorithm
12 Write a program to implement Breadth First search
13 Write a program to implement Depth First search
14 Write a program to implement Topological sorting
15 Write a program to implement Subset Sum problem using Backtracking
16 Write a program to implement N Queens problem using Backtracking
EXERCISE 1
1. Write a program to find GCD of two numbers using different algorithms

Euclid’s Algorithm and Consecutive Integer Checking Algorithm

def gcde(m,n):
if m< n:
(m,n) = (n,m)
while n!=0:
r=m % n
m=n
n=r
return m

def gcdc(m,n):
t=min(m, n)
while t > 0:
if m % t == 0 and n % t == 0:
return t
t =t - 1

print("Program to find the GCD of 2 numbers using:")


print("1: Euclid's Algorithm")
m = int(input("enter first number: "))
n = int(input("enter second number: "))
print(gcde(m,n))
print("2: Consecutive Integer Checking Algorithm")
m = int(input("enter first number: "))
n = int(input("enter second number: "))
print(gcdc(m,n))

Explanation:

The program takes two numbers and prints the GCD of two numbers.
def : It is used to define the function in python , which can take the arguments.
input(): Function is used to take input from the user
int(input) :To take integer input in Python. The Python’s built-in input () function
always returns a str(string) class object. So for taking integer input we have to type cast
those inputs into integers by using Python built-in int () function.

Euclid Algorithm :
1.Take two numbers from the user.
2. Pass the two numbers as arguments to a recursive function.
If m < n ,interchange as we do m % n
3. When the second number becomes 0, return the first number.
4. Else recursively call the function with the arguments as the second number and
the remainder when the first number is divided by the second number.
5. Return the first number which is the GCD of the two numbers.
6. Print the GCD.
7. Exit.

Consecutive Integer Checking


Step 1. Assign the value of min{m,n} to t
Step 2. Divide m by t. If the remainder of this division is 0, go to
Step 3; otherwise go to Step 4.
Step 3. Divide n by t. If the remainder of this division is 0, return the value of t as the answer
and step, otherwise, proceed to Step 4.
Step 4. Decrease the value of t by 1. Go to Step 2.
EXERCISE 2
2. Write a program to Implement Sieve of Eratosthenes to generate Prime Numbers Between Given
Range

def SieveOfEratosthenes(n):

prime = [True for i in range(n + 1)]


p=2
while (p * p <= n):

if (prime[p] == True):

for i in range(p * 2, n + 1, p):


prime[i] = False
p += 1
prime[0]= False
prime[1]= False
for p in range(n + 1):
if prime[p]:
print p,

if name ==' main ':


n = 30
print "Following are the prime numbers "
SieveOfEratosthenes(n)

Explanation:

Prime = [True for i in range(n+1) : Print True for all till n value
It is one of the simple, ancient algorithm for finding all prime numbers up to any given limit.
The Steps in simple form
Mark the table with all true values initially and later follow the given steps
1. Generate numbers from 2 to n (2 is the smallest prime).
2. Traverse from smallest prime number which is num = 2.
3. Eliminate or mark all the multiples of num (as 0 or -1) which are lesser than or equal to n. It
will help remove non-prime numbers and will help to reduce our number of comparisons to
check for each number.
4. Update the value of num to the immediate next prime number. The next prime is the next
(non 0 or -1) number in the list which is greater than the current number (num).
5. Repeat step three until num<=√n.
Traverse the whole list and number print. All the numbers (>=0) will be our required prime
numbers lesser than n (given number).

Example for prime number using Sieve of Eratosthenes


EXERCISE 3
3. Write a program to implement string matching using Brute force

def search(pat, txt):


M = len(pat)
N = len(txt)
# A loop to slide pat[] one by one */
for i in range(N - M + 1):
j=0
# For current index i,
check # for pattern match
*/ while(j < M):
if (txt[i + j] != pat[j]):
break
j += 1

if (j == M):
print("Pattern found at index ", i)

if name == ' main ': txt


= input("Enter the text:")
pat = input("Enter the pattern:")
search(pat, txt)

Explanation:

do
if (text letter == pattern letter)
compare next letter of pattern to next
letter of text
else
move pattern down text by one letter
while (entire pattern found or end of text)

M= length of the pattern , N= Length of the Text.

Example :

1) AAAAAAAAAAAAAAAAAAAAAAAAAAAH AAAAH 5 comparisons made


2) AAAAAAAAAAAAAAAAAAAAAAAAAAAH AAAAH 5 comparisons made
3) AAAAAAAAAAAAAAAAAAAAAAAAAAAH AAAAH 5 comparisons made
4) AAAAAAAAAAAAAAAAAAAAAAAAAAAH AAAAH 5 comparisons made
5) AAAAAAAAAAAAAAAAAAAAAAAAAAAH AAAAH 5 comparisons made

.... N)
AAAAAAAAAAAAAAAAAAAAAAAAAAAH 5 comparisons made
AAAAH
Time Complexity

• Total number of comparisons: M (N-M+1)


• Worst case time complexity: Ο(MN)
EXERCISE 4
4. Write a program to implement Merge Sort

def merge_sort(alist, start, end):


'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end)

def merge_list(alist, start, mid, end):


left = alist[start:mid]
right = alist[mid:end]
k = start
i=0
j=0
while (start + i < mid and mid + j < end):
if (left[i] <= right[j]):
alist[k] = left[i]
i=i+1
else:
alist[k] = right[j]
j=j+1
k=k+1
if start + i < mid:
while k < end:
alist[k] = left[i]
i=i+1
k=k+1
else:
while k < end:
alist[k] = right[j]
j=j+1
k=k+1

alist = input('Enter the list of numbers: ').split()


print(alist)
alist = [int(x) for x in alist]
merge_sort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)

Explanation :

Step 1 − if it is only one element in the list it is already sorted, return.


Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.

The split() method splits a string into a list.


print('Sorted list: ', end='') : ends the output with a space

Time Complexity : Worst,Best, Avg case : O(n log n)


EXERCISE 5
5. Write a program to implement Quick Sort

def quicksort(alist, start, end):

'''Sorts the list from indexes start to end - 1 inclusive.'''

if end - start > 1:

p = partition(alist, start, end)

quicksort(alist, start, p)

quicksort(alist, p + 1, end)

def partition(alist, start, end):

pivot = alist[start]

i = start + 1

j = end - 1

while True:

while (i <= j and alist[i] <= pivot):

i=i+1

while (i <= j and alist[j] >= pivot):

j=j-1

if i <= j:

alist[i], alist[j] = alist[j], alist[i]

else:

alist[start], alist[j] = alist[j], alist[start]

return j

alist = input('Enter the list of numbers: ').split()

alist = [int(x) for x in alist]

quicksort(alist, 0, len(alist))

print('Sorted list: ', end='')

print(alist)

Explanation : Refer the link https://www.geeksforgeeks.org/quick-sort/

Time Complexity : Best and Avg case : O(n log n),Worst Case :O(n 2)
EXERCISE 6

6. Write a program to obtain minimum cost spanning tree using Prim’s Algorithm
# Prim's Algorithm in Python
INF = 9999999
# number of vertices in graph
V=5
# create a 2d array of size 5x5
# for adjacency matrix to represent graph
G = [[0, 9, 75, 0, 0],
[9, 0, 95, 19, 42],
[75, 95, 0, 51, 66],
[0, 19, 51, 0, 31],
[0, 42, 66, 31, 0]]
# create a array to track selected vertex
# selected will become true otherwise false
selected = [0, 0, 0, 0, 0]
# set number of edge to 0
no_edge = 0
# the number of egde in minimum spanning tree will be
# always less than(V - 1), where V is number of vertices in
# graph
# choose 0th vertex and make it true
selected[0] = True
# print for edge and weight
print("Edge : Weight\n")
while (no_edge < V - 1):
# For every vertex in the set S, find the all adjacent vertices
#, calculate the distance from the vertex selected at step 1.
# if the vertex is already in the set S, discard it otherwise
# choose another vertex nearest to selected vertex at step 1.
minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
# not in selected and there is an edge
if minimum > G[i][j]:
minimum = G[i][j]
x=i
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1
Explanation : Pseudocode

VT ← {v0} //the set of tree vertices can be initialized with any vertex
ET ← ∅
for i ← 1 to |V | − 1 do
find a minimum-weight edge e∗ = (v∗, u∗) among all the edges (v, u)
such that v is in VT and u is in V − VT
VT ← VT ∪ {u∗}
ET ← ET ∪ {e∗}
return ET

Steps:

1. Select a starting vertex  
2. Step 2: Repeat Steps 3 and 4 until there are fringe vertices  
3. Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex (there exists an edge
from a tree vertex, or unseen )that has minimum weight  
4. Step 4: Add the selected edge and the vertex to the minimum spanning tree T  
5. [END OF LOOP] 

Time Complexity

Adjacency matrix, linear searching O(|V|2)


Adjacency list and binary heap O(|E| log |V|)

EXERCISE 7
7. Write a program to obtain minimum cost spanning tree using Kruskal’s Algorithm

class Graph:
def init (self, vertices):
self.V = vertices
self.graph = []

def add_edge(self, u, v, w):


self.graph.append([u, v, w])

# Search function

def find(self, parent, i):


if parent[i] == i:
return i
return self.find(parent, parent[i])

def apply_union(self, parent, rank, x, y):


xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1

def kruskal_algo(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in
range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
for u, v, weight in result:
print("%d - %d: %d" % (u, v, weight))
g = Graph(6)
g.add_edge(0, 1, 4)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 2)
g.add_edge(1, 0, 4)
g.add_edge(2, 0, 4)
g.add_edge(2, 1, 2)
g.add_edge(2, 3, 3)
g.add_edge(2, 5, 2)
g.add_edge(2, 4, 4)
g.add_edge(3, 2, 3)
g.add_edge(3, 4, 3)
g.add_edge(4, 2, 4)
g.add_edge(4, 3, 3)
g.add_edge(5, 2, 2)
g.add_edge(5, 4, 3)
g.kruskal_algo()

Refer for example (Union and Find ) :


https://www.simplilearn.com/tutorials/data-structure-tutorial/kruskal-algorithm.

Explanation :

Steps:
First, sort all the edges from low weight to high.
Now, take the edge with the lowest weight and add it to the spanning tree. If the edge to be added
creates a cycle, then reject the edge.
Continue to add the edges until we reach all vertices, and a minimum spanning tree is created.

Pseudocode :

//Kruskal’s algorithm for constructing a minimum spanning tree


//Input: A weighted connected graph G = V,E
//Output: ET , the set of edges composing a minimum spanning tree of G
sort E in nondecreasing order of the edge weights w(ei1 ) ≤ ... ≤ w(ei|E| )
ET ← ∅; ecounter ← 0 //initialize the set of tree edges and its size
k ← 0 //initialize the number of processed edges
while ecounter < |V | − 1 do
k←k+1
if ET ∪ {eik} is acyclic
ET ← ET ∪ {eik }; ecounter ← ecounter + 1
return ET .

Time complexity is O(E log V)

sorted(self.graph, key=lambda item: item[2])

A lambda function can take any number of arguments, but can only have one expression.
lambda arguments : expression
lambda function includes three elements:

● The keyword lambda — an analog of def in normal functions


● The parameters — support passing positional and keyword
arguments, just like normal functions
● The body — the expression for given parameters being evaluated
with the lambda function.

Lambda has used inside the sorted() function to sort the list. The graph is given as the first
argument value, the lambda has been set as the key value,
This will sort the graph edges based on the second item of each tuple and the print() function
has used to print the sorted list with space.
EXERCISE 8
8. Write a program to obtain shortest path using Djikstra’s algorithm

import sys

class Graph():
def __init (self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]

def printSolution(self, dist):


print("Vertex tDistance from Source")
for node in range(self.V):
print(node, "t", dist[node])

def minDistance(self, dist, sptSet):


min = sys.maxsize
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index

def dijkstra(self, src):


dist = [sys.maxsize] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
u = self.minDistance(dist, sptSet)
sptSet[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]:
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)

g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]

g.dijkstra(0)
Explanation :

● Create a set sptSet (shortest path tree set) that keeps track of vertices included in the
shortest-path tree, i.e., whose minimum distance from the source is calculated and
finalized. Initially, this set is empty. 
● Assign a distance value to all vertices in the input graph. Initialize all distance values
as INFINITE. Assign the distance value as 0 for the source vertex so that it is picked first. 
● While sptSet doesn’t include all vertices 
● Pick a vertex u which is not there in sptSet and has a minimum distance value. 
● Include u to sptSet. 
● Then update distance value of all adjacent vertices of u. 
● To update the distance values, iterate through all adjacent vertices. 
● For every adjacent vertex v, if the sum of the distance value of u
(from source) and weight of edge u-v, is less than the distance value
of v, then update the distance value of v. 

Self Keyword

The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class.

The sys module in Python provides valuable information about the Python interpreter. You can also
use it to obtain details about the constants, functions and methods of the Python interpreter.

maxsize attribute of the sys module fetches the largest value a variable of data type Py_ssize_t can


store. It is the Python platform’s pointer that dictates the maximum size of lists and strings in Python.
The size value returned by maxsize depends on the platform architecture:
● 32-bit: the value will be 2^31 – 1, i.e. 2147483647
● 64-bit: the value will be 2^63 – 1, i.e. 9223372036854775807.

Time Complexity :

Matrix representation is O(V^2).


Adjacency list representation O(ELogV) .
EXERCISE 9
9. Write a program to compute Binomial Coefficient

def binomialCoef(n, k):

C = [[0 for x in range(k+1)] for x in range(n+1)]


for i in range(n+1):
for j in range(min(i, k)+1):
# Base Cases
if j == 0 or j == i:
C[i][j] = 1
else:
C[i][j] = C[i-1][j-1] + C[i-1][j]
return C[n][k]

n=5
k=2
print("Value of C[" + str(n) + "][" + str(k) + "] is " + str(binomialCoef(n, k)))

Explanation :

Algorithm BINO(n, k)
// n is total number of items
// k is the number of items to be selected from n

if k == 0 or k == n then
return 1
else
return _BINO(n – 1, k – 1) + BINO(n – 1, k)
end

Time Complexity : T(n,k) = O(nk)


EXERCISE 10
10. Write a program to obtain shortest path using Floyds algorithms

import sys
INF = sys.maxsize
def floydWarshall(graph):
# number of vertices in the graph
n = len(graph)
# dist will be the output matrix that will have the shortest distances between every pair of vertex.
dist = [[] for i in range(n)]
# Initialize the dist matrix as same as the input graph matrix.
for i in range(n):
for j in range(n):
dist[i].append(graph[i][j])
# Taking all vertices one by one and setting them as intermediate vertices
for k in range(n):
# Pick all vertices as source one by one.
for i in range(n):
# Pick all vertices as the destination for the above choosen source vertex.
for j in range(n):
# Update the value of dist[i][j] if k provides a shortest path from i to j
dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j])
# Shortest distance for every pair of vertex.
print('Shortest Distance between every pair of vertex:-')
for i in range(n):
for j in range(n):
if dist[i][j]==INF:
print ("%7s" % ("INF"),end=' ')
else:
print ("%7s" % (dist[i][j]),end=' ')
print()

graph = [[0,5,INF,10],[INF,0,3,INF],[INF,INF,0,1],[INF,INF,INF,0]]
floydWarshall(graph)

Explanation :

FLOYD - WARSHALL (W)


1. n ← rows [W].
2. D0 ← W
3. for k ← 1 to n
4. do for i ← 1 to n
5. do for j ← 1 to n
6. do dij(k) ← min (dij(k-1),dik(k-1)+dkj(k-1) )
7. return D(n)

Time Complexity:- O(V3).


EXERCISE 11
11. Write a program to compute Transitive closure using Warshall’s algorithm

#from collections import defaultdict

class Graph:
def init (self, vertices): self.V
= vertices

def printSolution(self, reach):


print ("Following matrix transitive closure of the given graph ")
for i in range(self.V):
for j in range(self.V):
if (i == j):
print ("%7d\t" % (1))
else:
print ("%7d\t" %(reach[i][j]))
print ("")

def transitiveClosure(self,graph):
reach =[i[:] for i in graph]
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
reach[i][j] = reach[i][j] or (reach[i][k] and reach[k]

[j]) self.printSolution(reach)

g= Graph(4)
graph = [[1, 1, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]]

g.transitiveClosure(graph)

Algorithm :
Warshall(A[1...n, 1...n]) // A is the adjacency matrix
R(0) ← A
for k ← 1 to n do
for i ← 1 to n do
for j ← to n do
R(k)[i, j] ← R(k-1)[i, j] or (R(k-1)[i, k] and R(k-1)[k, j])
return R(n)

Time Complexity:- O(V3).


EXERCISE 12
12. Write a program to implement Breadth First search

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

Explanation :
create a queue Q 
mark v as visited and put v into Q 
while Q is non-empty 
    remove the head u of Q 
    mark and enqueue all (unvisited) neighbors of u

Time Complexity : O(V+E) 


EXERCISE 13
13. Write a program to implement Depth First search

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of


graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')

Explanation :

DFS(G, u)
    u.visited = true
    for each v ∈ G.Adj[u]
        if v.visited == false
            DFS(G,v)   
init() {
    For each u ∈ G
        u.visited = false
     For each u ∈ G
       DFS(G, u)
}

Time Complexity : O(V+E) 


EXERCISE 14
14. Write a program to implement Topological sorting

from collections import defaultdict

class Graph:
def __init (self,vertices):
self.graph = defaultdict(list) #dictionary containing adjacency List
self.V = vertices #No. of vertices

def addEdge(self,u,v):
self.graph[u].append(v)
def topologicalSortUtil(self,v,visited,stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
stack.insert(0,v)

def topologicalSort(self):
visited = [False]*self.V
stack =[]
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
print stack

g= Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);

print "Following is a Topological Sort of the given graph"


g.topologicalSort()

Explanation :
Time Complexity : O(V+E) 
EXERCISE 15
15. Write a program to implement Subset Sum problem using Backtracking

def isSubsetSum(set, n, sum) :

if (sum == 0) :
return True
if (n == 0 and sum != 0) :
return False

if (set[n - 1] > sum) :


return isSubsetSum(set, n - 1, sum);

return isSubsetSum(set, n-1, sum) or isSubsetSum(set, n-1, sum-set[n-1])

set = [3, 34, 4, 12, 5, 2]


sum = 9
n = len(set)
if (isSubsetSum(set, n, sum) == True) :
print("Found a subset with given sum")
else :
print("No subset with given sum")

Explanation :
1. Start with an empty set
2. Add the next element from the list to the set
3. If the subset is having sum M, then stop with that subset as solution.
4. If the subset is not feasible or if we have reached the end of the set, then backtrack through the
subset until we find the most suitable value.
5. If the subset is feasible (sum of seubset < M) then go to step 2.
6. If we have visited all the elements without finding a suitable subset and if no backtracking is
possible then stop without solution.

Pseducode
void subset_sum(int list[], int sum, int starting_index, int target_sum)
{
if( target_sum == sum )
{
subset_count++;
if(starting_index < list.length)
subset_sum(list, sum - list[starting_index-1], starting_index, target_sum);
}
else
{
for( int i = starting_index; i < list.length; i++ )
{
subset_sum(list, sum + list[i], i + 1, target_sum);
}
}
}
Time complexity : O(2^N) 
EXERCISE 16
16. Write a program to implement N Queens problem using Backtracking

# Taking number of queens as input from user


print ("Enter the number of queens")
N = int(input())
# here we create a chessboard
# NxN matrix with all elements set to 0
board = [[0]*N for _ in range(N)]
def attack(i, j):
#checking vertically and horizontally
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
#checking diagonally
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False
def N_queens(n):
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)

Refer to understand the concept https://www.youtube.com/watch?


v=u6viVC1fJ9g

Steps for queen program


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 the queen in [row, column] leads to
a solution then return true.
c) If placing queen doesn't lead to a solution then
unmark 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.

Time Complexity : O(N!)

You might also like