DAA Manual
DAA Manual
DAA Manual
Prepared by Approved by
Mrs.Anjali Vyas Dr.S.P.Manikandan
HOD-CE
INSTITUTION
Vision
To emerge as an institute of eminence in the fields of engineering, technology and management in serving the
industry and the nation by empowering students with a high degree of technical, managerial and practical
competence.
Mission
To strengthen the theoretical, practical and ethical dimensions of the learning process by fostering a culture of
research and innovation among faculty members and students.
To encourage long-term interaction between the academia and industry through their involvement in the design of
curriculum and its hands-on implementation.
To strengthen and mould students in professional, ethical, social and environmental dimensions by
encouraging participation in co-curricular and extracurricular activities.
To develop value based socially responsible professionals for the betterment of the society
Quality Policy
To emerge as an institute of eminence in the fields of engineering, technology and management in serving the
industry and the nation by empowering students with a high degree of technical, managerial and practical
competence.
Values
Academic Freedom Professionalism
Innovation Inclusiveness
Integrity Social Responsibility
DEPARTMENT OF COMPUTER ENGINEERING
Vision
To produce engineers, researchers and technologists with managerial skills of highest competence who would
be able to solve the challenges of society.
Mission
To impart high quality professional training, practical experience and value education in the Computer
Engineering.
To pursue creative research in Computer Engineering in order to serve the engineering community and
society.
To prepare and encourage a student for Lifelong learning to meet career and ethical challenges through active
participation in co-curricular and extracurricular activities.
Program Educational Objectives (PEOs)
To prepare globally competent graduates having strong fundamentals of Computer
PEO1: Engineering domain knowledge, updated with modern technology to provide effective
solutions for engineering problems.
PEO2: To acuminate graduates with ability to adapt and develop projects towards the latest
technological era of the Computing and IT sector with a high degree of innovative ideas.
PEO3: To produce committed and motivated graduates with research attitude, investigative
approach, and multidisciplinary thinking for implementation of strategic tasks.
PEO 4: To shape the graduates with strong managerial and communication skills to work and
learn continuously and effectively as individuals as well as in teams.
PEO to Mission Statement Mapping
PSO1: The ability to apply the knowledge of core science, engineering mathematics and engineering
fundamentals to design and develop the computing systems.
PSO2: The ability to provide effective and efficient real time solutions to problems in computer engineering
using acquired knowledge in various domains
Program Outcomes (POs) with Graduate Attributes
Engineering knowledge: Apply the knowledge of mathematics, science, Engineering
PO1 fundamentals, and an Engineering specialization to the solution of complex
Engineering problems in Computer Engineering.
Problem analysis: Identify, formulate, review research literature, and analyze
PO2 complex Engineering problems in Computer Engineering reaching substantiated
conclusions using first principles of mathematics, natural sciences, and Engineering
sciences.
Design / Development of Solutions: Design solutions for complex Engineering
PO3 problems and design system components or processes of Computer Engineering that
meet the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and Environmental considerations.
Conduct Investigations of Complex Problems: Use research-based knowledge and
PO4 research methods including design of experiments in Computer Engineering, analysis
and interpretation of data, and synthesis of the information to provide valid conclusions.
Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
PO5 modern Engineering and IT tools including prediction and modeling to complex
Engineering activities in Computer Engineering with an understanding of the
limitations.
The Engineer and Society: Apply reasoning informed by the contextual knowledge
PO6 to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice in Computer
Engineering.
Environment and Sustainability: Understand the impact of the professional
PO7 Engineering solutions of Computer Engineering in societal and Environmental
contexts, and demonstrate the knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities
PO8
and norms of the Engineering practice.
Individual and Team Work: Function effectively as an individual, and as a member
PO9
or leader in diverse teams, and in multidisciplinary settings.
Communication Skills: Communicate effectively on complex Engineering activities
PO10 with the Engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
Project Management and Finance: Demonstrate knowledge and understanding of the
PO11 Engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary Environments.
Life-long Learning: Recognize the need for, and have the preparation and ability to
PO12 engage in independent and life-long learning in the broadest context of technological
change.
LAB RUBRICS
1. Continuous Assessment:
i) Will be carried out in every lab (for labs -12 programs)
ii) Each program will be evaluated for 10 marks
iii) Totally for 12 lab programs it will be 120 marks. This will be scaled down to 10.
iv) During the semester, 2 internal tests will be conducted for 50 marks each. The total 50 marks for
the internal tests, will be scaled down to 40.
Not written 1
Answers correctly 2
Viva Voce (2)
Answers satisfactorily 1
Do not answer any question 0
2. Internal Test:
Break up of 50 marks (for each of the 2 internal tests) which is scaled down to 40 marks after the
conduction of 2 internal tests:
The 1st lab internal will comprise of the first 8 lab programs and the 2nd lab internal will comprise of
the next 7 lab programs.
Attributes Descriptors Scores
Complete program with proper variable naming, proper
5
commenting
Complete program with not so proper variable naming,
3-4
Program poor commenting
Write-up (5)
Incomplete code 1-2
Not written 0
Assessment Marks: 25
Not written 0
Course Outcomes: At the end of the Course, the Student will be able to
CO# COURSE OUTCOME
21CEL47A.1 Write the complexities of various applications in different domains
21CEL47A.2 Apply efficient algorithms to solve problems in various domains
21CEL47A.3 Analyze suitable design technique to develop efficient algorithms
21CEL47A.4 Compare, implement and understand when to apply various design techniques
Assessment Pattern
CIE- Continuous Internal Evaluation (50 Marks)
Algorithm:
Program:
#include <stdio.h>
int main() {
int a, b;
printf("Enter two positive integers: ");
scanf("%d %d", &a, &b);
return 0;
}
Output:
Enter two positive integers: 5 10
GCD = 5
2. Write a program to Implement Sieve of Eratosthenes to generate Prime Numbers
Between Given Range
Algorithm:
1. First, we ask the user to input the upper limit of the range.
2. We create a boolean array called "prime" of size n+1, and initialize all entries to true.
The array will store whether each number in the range is prime or composite.
3. We iterate over the array from 2 to the square root of n (inclusive). For each prime
number p, we mark all of its multiples as composite by setting their corresponding
entries in the "prime" array to false.
4. After the loop is finished, all entries in the "prime" array that are still true correspond
to prime numbers between 2 and n. We print them out using a loop.
5. The program ends by returning 0.
Program:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main()
{ int n = 30;
printf("Following are the prime numbers smaller than or equal to %d \n", n);
SieveOfEratosthenes(n);
return 0;}
Output:
Following are the prime numbers smaller than or equal to 30
2 3 5 7 11 13 17 19 23 29
3. Write a program to implement string matching using Brute Force
Algorithm:
1. First, we ask the user to input the text string and the pattern string.
2. We create a function called "stringMatch" that takes two arguments: the text string
and the pattern string.
3. Inside the stringMatch function, we initialize two variables "i" and "j" to 0. We also
get the lengths of the text and pattern strings and store them in variables "n" and "m".
4. We iterate over the text string using a for loop that starts at index 0 and ends at index
n - m. This is because we don't need to check the last m characters of the text string,
since the pattern can't match there.
5. Inside the first for loop, we iterate over the pattern string using a nested for loop. We
compare each character of the pattern string with the corresponding character of the
text string starting at index i.
6. If any characters don't match, we break out of the loop and move on to the next
iteration of the outer loop.
7. If all characters in the pattern string match the corresponding characters in the text
string, we print out the index where the pattern was found.
8. In the main function, we call the stringMatch function with the text and pattern strings
as arguments.
9. The program ends by returning 0.
Program:
#include <stdio.h>
#include <string.h>
void stringMatch(char* text, char* pattern) {
int i, j;
int n = strlen(text);
int m = strlen(pattern);
// Iterate over the text string, checking for matches with the pattern
for (i = 0; i <= n - m; i++) {
// Iterate over the pattern, comparing each character with the corresponding character in the
text
for (j = 0; j < m; j++) {
if (text[i+j] != pattern[j])
break;
}
// If all characters in the pattern match the corresponding characters in the text,
// then we have found a match
if (j == m)
printf("Pattern found at index %d\n", i);
}
}
int main() {
char text[1000], pattern[1000];
Output:
Algorithm:
1. We define a function called "merge" that takes four arguments: the array to be
sorted, the left index of the subarray, the middle index of the subarray, and the
right index of the subarray.
2. Inside the "merge" function, we first calculate the sizes of the left and right
subarrays. We then create temporary arrays to store the left and right subarrays.
3. We copy the data from the main array into the temporary arrays.
4. We then merge the temporary arrays back into the main array by comparing the
first elements of each subarray and copying the smaller element into the main
array.
5. Finally, we copy any remaining elements of the left or right subarray into the main
array.
6. We define a function called "mergeSort" that takes three arguments: the array to
be sorted, the left index of the subarray, and the right index of the subarray.
7. Inside the "mergeSort" function, we first check if the left index is less than the
right index. If not, then the subarray is already sorted and we can exit the function.
Program:
#include <stdio.h>
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
// Copy any remaining elements of the right subarray into the main array
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
mergeSort(arr, 0, n - 1);
printf("\nSorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output:
Original array: 38 27 43 3 9 82 10
Sorted array: 3 9 10 27 38 43 82
5. Write a program to implement Quick Sort
Algorithm:
1. We define a function called "swap" that takes two integer pointers as arguments and
swaps the values at those pointers.
2. We define a function called "partition" that takes three arguments: the array to be
sorted, the left index of the subarray, and the right index of the subarray.
3. Inside the "partition" function, we choose the last element of the subarray as the pivot.
We then loop through the subarray, moving elements smaller than the pivot to the left
of the pivot.
4. After the loop, we swap the pivot with the element immediately to its right, which
puts the pivot in its final sorted position. We then return the index of the pivot.
5. We define a function called "quickSort" that takes three arguments: the array to be
sorted, the left index of the subarray, and the right index of the subarray.
6. Inside the "quickSort" function, we first check if the left index is less than the right
index. If not, then the subarray is already sorted and we can exit the function.
7. We partition the subarray using the "partition" function, which gives us the index of
the pivot.
8. We then recursively call "quickSort" on the left subarray and the right subarray, using
the pivot index as the dividing point.
9. We define the main function, which creates an array, prints the original array, sorts the
array using quickSort, and then prints the sorted array.
Program:
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
return 0;
}
Output:
Original array: 38 27 43 3 9 82 10
Sorted array: 3 9 10 27 38 43 82
6. Write a program to obtain minimum cost spanning tree using Prim’s Algorithm
Algorithm:
1. We define a function called "minKey" that takes two arrays as arguments: an array of
key values for each vertex, and an array indicating whether each vertex is in the
minimum spanning tree set.
2. Inside the "minKey" function, we loop through all the vertices and find the vertex
with the minimum key value that is not yet in the minimum spanning tree set.
3. We define a function called "printMST" that takes two arrays as arguments: an array
of parent vertices and the adjacency matrix representing the graph.
4. Inside the "printMST" function, we loop through all the vertices except the root (0),
and print the edge connecting each vertex to its parent, along with its weight.
5. We define a function called "primMST" that takes the adjacency matrix representing
the graph as an argument.
6. Inside the "primMST" function, we initialize three arrays: an array of parent vertices,
an array of key values for each vertex, and an array indicating whether each vertex is
in the minimum spanning tree set.
7. We set the key value of the root vertex (0) to 0, and its parent to -1, and set the key
value of all other vertices to INT_MAX.
8. We loop through all the vertices except the root (0), and find the vertex with the
minimum key value that is not yet in the minimum spanning tree set using the
"minKey" function
Program:
#include <stdio.h>
#include <limits.h>
return min_index;
}
printMST(parent, graph);
}
int main() {
int graph[V][V] = {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}};
primMST(graph);
return 0;
}
Output:
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
7. Write a program to obtain minimum cost spanning tree using Kruskal’s Algorithm
In Kruskal’s algorithm, sort all edges of the given graph in increasing order. Then it keeps on
adding new edges and nodes in the MST if the newly added edge does not form a cycle. It
picks the minimum weighted edge at first at the maximum weighted edge at last. Thus we can
say that it makes a locally optimal choice in each step in order to find the optimal solution.
Hence this is a Greedy Algorithm.
Program:
#include <stdio.h>
#include <stdlib.h>
return parent[component]
= findParent(parent, parent[component]);
}
int parent[n];
int rank[n];
printf(
"Following are the edges in the constructed MST\n");
for (int i = 0; i < n; i++) {
int v1 = findParent(parent, edge[i][0]);
int v2 = findParent(parent, edge[i][1]);
int wt = edge[i][2];
// Driver code
int main()
{
int edge[5][3] = { { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };
kruskalAlgo(5, edge);
return 0;
}
Output:
Output: 0 4 12 19 21 11 9 8 14
Explanation: The distance from 0 to 1 = 4.
The minimum distance from 0 to 2 = 12. 0->1->2
The minimum distance from 0 to 3 = 19. 0->1->2->3
The minimum distance from 0 to 4 = 21. 0->7->6->5->4
The minimum distance from 0 to 5 = 11. 0->7->6->5
The minimum distance from 0 to 6 = 9. 0->7->6
The minimum distance from 0 to 7 = 8. 0->7
The minimum distance from 0 to 8 = 14. 0->1->2->8
Like Prim’s MST, generate a SPT (shortest path tree) with a given source as a root. Maintain
two sets, one set contains vertices included in the shortest-path tree, other set includes
vertices not yet included in the shortest-path tree. At every step of the algorithm, find a vertex
that is in the other set (set not yet included) and has a minimum distance from the source.
1. 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.
2. 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.
3. While sptSet doesn’t include all vertices
4. Pick a vertex u that is not there in sptSet and has a minimum distance value.
5. Include u to sptSet.
6. Then update the distance value of all adjacent vertices of u.
7. To update the distance values, iterate through all adjacent vertices.
8. 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.
Note: We use a boolean array sptSet[] to represent the set of vertices included in SPT. If a
value sptSet[v] is true, then vertex v is included in SPT, otherwise not. Array dist[] is used to
store the shortest distance values of all vertices.
Program:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
return min_index;
}
// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 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 } };
dijkstra(graph, 0);
return 0;
}
Output:
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
9. Write a program to compute Binomial Coefficient
Algorithm:
Program:
#include <stdio.h>
int binomialCoeff(int n, int k) {
if (k == 0 || k == n)
return 1;
else
return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);
}
int main() {
int n = 5, k = 2;
printf("Binomial Coefficient of (%d,%d) is %d", n, k, binomialCoeff(n, k));
return 0;
}
Output:
Algorithm:
1. The printMatrix function takes a matrix as input and prints it to the console.
2. The transitiveClosure function takes the adjacency matrix of a directed graph as
input and computes its transitive closure using Warshall's algorithm.
3. It initializes the transitive closure matrix with the adjacency matrix and updates it
using the algorithm.
4. The main function initializes the adjacency matrix of a directed graph, calls the
transitiveClosure function to compute its transitive closure, and prints the
resulting matrix to the console.
Program:
#include <stdio.h>
#define V 4 // Number of vertices in the graph
void printMatrix(int matrix[][V]) {
printf("Transitive Closure Matrix:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++)
printf("%d ", matrix[i][j]);
printf("\n"); }}
void transitiveClosure(int graph[][V]) {
int tc[V][V]; // Initialize transitive closure matrix with the adjacency matrix
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
tc[i][j] = graph[i][j];
int main() {
int graph[V][V] = {{1, 1, 0, 1},
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}}; // Adjacency matrix of the directed graph
transitiveClosure(graph); // Compute transitive closure
return 0;}
Output:
Transitive Closure Matrix:
1111
0110
0011
0001
11. Write a program to implement Breadth First search
Algorithm:
1. The enqueue function takes a vertex as input and adds it to the rear of the queue.
2. The dequeue function removes and returns the front element of the queue.
3. The bfs function takes the starting vertex and the number of vertices in the graph
as input and performs BFS on the graph starting from the given vertex.
4. It uses the enqueue and dequeue functions to add and remove vertices from the
queue.
5. The visited array keeps track of the visited vertices, and the adj array is the
adjacency matrix of the graph.
6. The main function takes the adjacency matrix and the starting vertex as input and
calls the bfs function to perform BFS on the graph starting from the given vertex.
Program:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
struct queue {
int items[SIZE];
int front;
int rear;
};
struct node {
int vertex;
struct node* next;
};
struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};
// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);
while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Creating a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}
if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}
int main() {
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
bfs(graph, 0);
return 0;
}
Output:
Queue contains
0 Resetting queue Visited 0
Queue contains
2 1 Visited 2
Queue contains
1 4 Visited 1
Queue contains
4 3 Visited 4
Queue contains
3 Resetting queue Visited 3
12. Write a program to implement Depth First search
Algorithm:
Program:
#include <stdio.h>
#include <stdlib.h>
struct node {
int vertex;
struct node* next;
};
struct Graph {
int numVertices;
int* visited;
// DFS algo
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}}
// Create a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Create graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
int main() {
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printGraph(graph);
DFS(graph, 2);
return 0;
}
Output:
Adjacency list of vertex 0
2 -> 1 ->
Algorithm:
Program:
#include<stdio.h>
#include<conio.h>
int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);}
for(i=0;i<n;i++){
indeg[i]=0;
flag[i]=0; }
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
for(i=0;i<n;i++){
if(a[i][k]==1)
indeg[k]--;
} }
count++;
} return 0;}
Output:
Algorithm:
1. i: Item index
2. sum: Sum of integers selected so far
3. remSum: Size of remaining problem i.e. (W - sum)
// Output: Solution tuple X
12. return 1
13. First recursive call represents the case when the current item is selected, and hence the
problem size is reduced by w[i].
14. Second recursive call represents the case when we do not select the current item.
Program:
#include <stdio.h>
#include <stdlib.h>
// inputs
// s - set vector
// t - tuplet vector
// s_size - set size
// t_size - tuplet size so far
// sum - sum so far
// ite - nodes count
// target_sum - sum to be found
void subset_sum(int s[], int t[],
int s_size, int t_size,
int sum, int ite,
int const target_sum)
{
total_nodes++;
// constraint check
if( ite + 1 < s_size && sum - s[ite] + s[ite+1] <= target_sum )
{
// Exclude previous added item and consider next candidate
subset_sum(s, t, s_size, t_size-1, sum - s[ite], ite + 1, target_sum);
}
return;
}
else
{
// constraint check
if( ite < s_size && sum + s[ite] <= target_sum )
{
// generate nodes along the breadth
for( int i = ite; i < s_size; i++ )
{
t[t_size] = s[i];
int total = 0;
free(tuplet_vector);
}
int main()
{
int weights[] = {15, 22, 14, 26, 32, 9, 16, 8};
int target = 53;
return 0;
}
Output:
8 9 14 22
8 14 15 16
15 16 22
Nodes generated 68
15. Write a program to implement N Queens problem using Backtracking
Algorithm:
1. Initialize an empty chessboard of size NxN.
2. Start with the leftmost column and place a queen in the first row of that column.
3. Move to the next column and place a queen in the first row of that column.
4. Repeat step 3 until either all N queens have been placed or it is impossible to place a
queen in the current column without violating the rules of the problem.
5. If all N queens have been placed, print the solution.
6. If it is not possible to place a queen in the current column without violating the rules
of the problem, backtrack to the previous column.
7. Remove the queen from the previous column and move it down one row.
8. Repeat steps 4-7 until all possible configurations have been tried.
Program:
#define N 4
#include <stdbool.h>
#include <stdio.h>
return true;
}
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
Output:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0