DATA STRUCTURES AND ALGORITHMS LAB NOVEMBER 2024
S.NO DATE PROGRAM NAME PAGENO SIGN
Data structures and algorithms
1. Array implementation of stacks 03
2. 07
Linked List implementation of Queues
3. Implementation of Heap Tree 13
4. Binary Tree Traversals 15
(Inorder, Preorder, Postorder)
5. Implementation of BFS 19
6. Implementation of DFS 26
7. Implementation of Merge sort using divide 30
and conquer
8. Implementation of Prim’s algorithm using 33
Greedy techniques
9. Implementation of n-queens problem using 36
Backtracking
DATA STRUCTURES& ALGORITHMS LAB November 2024
Data structure
&
Algorithms
2 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:01
Array Implementation of Stack
Aim:
To write a program for the array implementation of Stack in C.
Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Define a array stack of size max = 5
4) Display a menu listing stack operations.
5) Use if..else statement to check the conditions.
6) Compile the program filename.cpp.
7) Run the program.
8) Save the program with extension .cpp.
9) Stop the program.
3 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
4 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
5 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Output:
Enter the size of STACK[MAX=100]:10
STACK OPERATIONS USING ARRAY
--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1
Enter a value to be pushed:12
Enter the Choice:1
Enter a value to be pushed:24
Enter the Choice:1
Enter a value to be pushed:98
Enter the Choice:3
The elements in STACK
98
24
12
Press Next Choice
Enter the Choice:2
The popped elements is 98
Enter the Choice:3
The elements in STACK
24
12
Press Next Choice
Enter the Choice:4
EXIT POINT
Result:
Thus the program has been successfully obtained and the output is verified.
6 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:02
Linked list Implementation of Queues
Aim:
To write a program for the linked list implementation of Queue using in C.
Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Define a array stack of size max = 5
4) Display a menu listing Queues operations.
5) Use if..else statement to check the conditions.
6) Compile the program filename.cpp.
7) Run the program.
8) Save the program with extension .cpp.
9) Stop the program.
7 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
8 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
{
front = rear = NULL;
}
void queuesize()
{
printf("\n Queue size : %d", count);
}
/* Enqueing the queue */
void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
9 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
/* Displaying the queue elements */
void display()
{
front1 = front;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
/* Dequeing the queue */
void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
10 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
/* Returns the front element of queue */
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}
void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
11 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Output:
1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Exit
6 - Display
7 - Queue size
Enter choice : 1
Enter data : 14
Enter choice : 1
Enter data : 85
Enter choice : 1
Enter data : 38
Enter choice : 3
Front element : 14
Enter choice : 6
14 85 38
Enter choice : 7
Queue size : 3
Enter choice : 2
Dequed value : 14
Enter choice : 6
85 38
Enter choice : 7
Queue size : 2
Enter choice : 4
Queue not empty
Result:
Thus the program has been successfully obtained and the output is verified.
12 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:03
Implementation of heap tree
Aim:
To write a program for the Implementation of Heap Tree in C.
Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Define a array stack of size max = 5
4) Display a menu listing stack operations.
5) Use if..else statement to check the conditions.
6) Compile the program filename.cpp.
7) Run the program.
8) Save the program with extension .cpp.
9) Stop the program.
13 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include<stdio.h>
#include<limits.h>
int heap[1000000], heapSize;
void Init() {
heapSize = 0;
heap[0] = -INT_MAX;
}
void Insert(int element) {
heapSize++;
heap[heapSize] = element;
int now = heapSize;
while (heap[now / 2] > element) {
heap[now] = heap[now / 2];
now /= 2;
}
heap[now] = element;
}
int DeleteMin() {
int minElement, lastElement, child, now;
minElement = heap[1];
lastElement = heap[heapSize--];
for (now = 1; now * 2 <= heapSize; now = child) {
child = now * 2;
if (child != heapSize && heap[child + 1] < heap[child]) {
child++;
}
if (lastElement > heap[child]) {
heap[now] = heap[child];
} else
{
break;
}
}
heap[now] = lastElement;
return minElement;
}
int main() {
int number_of_elements;
printf("Program to demonstrate Heap\nEnter the number of elements: ");
scanf("%d", &number_of_elements);
int iter, element;
Init();
printf("Enter the elements: ");
for (iter = 0; iter < number_of_elements; iter++) {
14 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
scanf("%d", &element);
Insert(element);
}
printf("Elements deleted in a sequence: ");
for (iter = 0; iter < number_of_elements; iter++) {
printf("%d ", DeleteMin());
}
printf("\n");
return 0;
}
Output:
Program to demonstrate Heap
Enter the number of elements: 5
Enter the elements: 645 897 612 849 643
Elements deleted in a sequence: 612 643 645 849 897
Result:
Thus the program has been successfully obtained and the output is verified.
15 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:04
Binary tree traversals
(inorder, preorder, postorder)
Aim:
To write a program for the binary tree traversals in C.
Algorithm:
1. Start the Program.
2. Type the codings in Turbo C.
3. Use if..else statement to check the conditions.
4. Compile the program filename.cpp.
5. Run the program.
6. Save the program with extension .cpp.
7. Stop the program.
16 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int element;
struct node* left;
struct node* right;
};
struct node* createNode(int val)
{
struct node* Node = (struct node*)malloc(sizeof(struct node));
Node->element = val;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
void traversePreorder(struct node* root)
{
if (root == NULL)
return;
printf(" %d ", root->element);
traversePreorder(root->left);
traversePreorder(root->right);
}
void traverseInorder(struct node* root)
{
if (root == NULL)
return;
traverseInorder(root->left);
printf(" %d ", root->element);
traverseInorder(root->right);
}
void traversePostorder(struct node* root)
{
if (root == NULL)
return;
traversePostorder(root->left);
traversePostorder(root->right);
printf(" %d ", root->element);
}
int main()
17 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
{
struct node* root = createNode(36);
root->left = createNode(26);
root->right = createNode(46);
root->left->left = createNode(21);
root->left->right = createNode(31);
root->left->left->left = createNode(11);
root->left->left->right = createNode(24);
root->right->left = createNode(41);
root->right->right = createNode(56);
root->right->right->left = createNode(51);
root->right->right->right = createNode(66);
printf("\n The Preorder traversal of given binary tree is -\n");
traversePreorder(root);
printf("\n The Inorder traversal of given binary tree is -\n");
traverseInorder(root);
printf("\n The Postorder traversal of given binary tree is -\n");
traversePostorder(root);
return 0;
}
Output:
The Preorder traversal of given binary tree is -
36 26 21 11 24 31 46 41 56 51 66
The Inorder traversal of given binary tree is -
11 21 24 26 31 36 41 46 51 56 66
The Postorder traversal of given binary tree is -
11 24 21 31 26 41 51 66 56 46 36
Result:
Thus the program has been successfully obtained and the output is verified.
18 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:05
IMPLEMENTATION of BFS
Aim:
To write a program for the implementation of BFS in C.
Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Read number of array elements n.
4) Define array elements Ai, i = 0,1,2,…n–1.
5) Declare if Ai = search then found = 1.
6) Use if..else statement to check the conditions.
7) Compile the program filename.cpp.
8) Run the program.
9) Save the program with extension .cpp.
10) Stop the program.
19 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int vertex;
struct node *next;
};
struct node *createNode(int);
struct Graph
{
int numVertices;
struct node **adjLists;
int *visited;
};
struct Graph *createGraph(int vertices)
{
struct Graph *graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node *));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++)
{
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph *graph, int src, int dest)
{
struct node *newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
struct node *createNode(int v)
{
struct node *newNode = malloc(sizeof(struct node));
20 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
void printGraph(struct Graph *graph)
{
int v;
for (v = 0; v < graph->numVertices; v++)
{
struct node *temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp)
{
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
void bfs(struct Graph *graph, int startVertex)
{
struct node *queue = NULL;
graph->visited[startVertex] = 1;
enqueue(&queue, startVertex);
while (!isEmpty(queue))
{
printQueue(queue);
int currentVertex = dequeue(&queue);
printf("Visited %d ", currentVertex);
struct node *temp = graph->adjLists[currentVertex];
while (temp)
{
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0)
{
graph->visited[adjVertex] = 1;
enqueue(&queue, adjVertex);
}
temp = temp->next;
}
}
}
int isEmpty(struct node *queue)
{
return queue == NULL;
}
void enqueue(struct node **queue, int value)
21 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
{
struct node *newNode = createNode(value);
if (isEmpty(*queue))
{
*queue = newNode;
}
else
{
struct node *temp = *queue;
while (temp->next)
{
temp = temp->next;
}
temp->next = newNode;
}
}
int dequeue(struct node **queue)
{
int nodeData = (*queue)->vertex;
struct node *temp = *queue;
*queue = (*queue)->next;
free(temp);
return nodeData;
}
void printQueue(struct node *queue)
{
while (queue)
{
printf("%d ", queue->vertex);
queue = queue->next;
}
printf("\n");
}
int main(void)
{
struct Graph *graph = createGraph(6);
printf("\nWhat do you want to do?\n");
printf("1. Add edge\n");
printf("2. Print graph\n");
printf("3. BFS\n");
printf("4. Exit\n");
int choice;
scanf("%d", &choice);
while (choice != 4)
{
22 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
if (choice == 1)
{
int src, dest;
printf("Enter source and destination: ");
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
}
else if (choice == 2)
{
printGraph(graph);
}
else if (choice == 3)
{
int startVertex;
printf("Enter starting vertex: ");
scanf("%d", &startVertex);
bfs(graph, startVertex);
}
else
{
printf("Invalid choice\n");
}
printf("What do you want to do?\n");
printf("1. Add edge\n");
printf("2. Print graph\n");
printf("3. BFS\n");
printf("4. Exit\n");
scanf("%d", &choice);
}
return 0;
}
23 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Output:
What do you want to do?
1. Add edge
2. Print graph
3. BFS
4. Exit
1
Enter source and destination: 0 1
What do you want to do?
1. Add edge
2. Print graph
3. BFS
4. Exit
1
Enter source and destination: 0 2
What do you want to do?
1. Add edge
2. Print graph
3. BFS
4. Exit
1
Enter source and destination: 1 2
What do you want to do?
1. Add edge
2. Print graph
3. BFS
4. Exit
1
Enter source and destination: 2 3
What do you want to do?
1. Add edge
2. Print graph
3. BFS
4. Exit
2
24 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Adjacency list of vertex 0
2 -> 1 ->
Adjacency list of vertex 1
2 -> 0 ->
Adjacency list of vertex 2
3 -> 1 -> 0 ->
Adjacency list of vertex 3
2 ->
Adjacency list of vertex 4
Adjacency list of vertex 5
What do you want to do?
1. Add edge
2. Print graph
3. BFS
4. Exit
3
Enter starting vertex: 0
0
Visited 0 2 1
Visited 2 1 3
Visited 1 3
Visited 3
What do you want to do?
1. Add edge
2. Print graph
3. BFS
4. Exit
4
Result:
Thus the program has been successfully obtained and the output is verified.
25 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:06
IMPLEMENTATION of DFs
Aim:
To write a program for the implementation of DFS in C.
Algorithm:
1. Start the program.
2. Read number of array elements n.
3. Read array elements Ai.
4. Outer index i varies from second element to last element.
5. Insert the element into the appropriate position.
6. Display the array elements after each pass.
7. Display the sorted array elements.
8. Stop the program.
26 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node {
int data;
struct Node* next;
};
struct List {
struct Node* head;
};
struct Graph {
int vertices;
struct List* array;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->vertices = vertices;
graph->array = (struct List*)malloc(vertices * sizeof(struct List));
for (int i = 0; i < vertices; i++) {
graph->array[i].head = NULL;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
newNode = createNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
27 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
void DFS(struct Graph* graph, int vertex, bool visited[]) {
visited[vertex] = true;
printf("%d ", vertex);
struct Node* currentNode = graph->array[vertex].head;
while (currentNode) {
int adjacentVertex = currentNode->data;
if (!visited[adjacentVertex]) {
DFS(graph, adjacentVertex, visited);
}
currentNode = currentNode->next;
}
}
void DFSTraversal(struct Graph* graph, int* order, int orderSize) {
bool* visited = (bool*)malloc(graph->vertices * sizeof(bool));
for (int i = 0; i < graph->vertices; i++) {
visited[i] = false;
}
for (int i = 0; i < orderSize; i++) {
if (!visited[order[i]]) {
DFS(graph, order[i], visited);
}
}
free(visited);
}
int main() {
int vertices = 4;
struct Graph* graph = createGraph(vertices);
addEdge(graph, 2, 0);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 0, 1);
addEdge(graph, 3, 3);
addEdge(graph, 1, 3);
int order[] = {2, 0, 1, 3};
int orderSize = sizeof(order) / sizeof(order[0]);
printf("Following is Depth First Traversal (starting from vertex 2):\n");
DFSTraversal(graph, order, orderSize);
return 0;
}
28 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Output:
Following is Depth First Traversal (starting from vertex 2):
2013
Result:
Thus the program has been successfully obtained and the output is verified.
29 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:07
Implementation of merge sort using
divide and conquer
Aim:
To write a program for the implementation of Merge sort using Divide and Conquer in C.
Algorithm:
1. Start the program.
2. Read number of array elements n.
3. Read array elements Ai.
4. Outer index i varies from second element to last element.
5. Inner index j is used to compare elements to left of outer index.
6. Divide the array into 3 sequences: elements < x, x, elements >x.
7. Merge the sorted sub-arrays on to a single sorted array.
8. Insert the element into the appropriate position.
9. Display the array elements after each pass.
10. Display the sorted array elements.
11. Stop the program.
30 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
31 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Result:
Thus the program has been successfully obtained and the output is verified.
32 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:08
ImplementatIon of prIm’s algorIthm usIng
greedy techniques
Aim:
To write a program for the implementation of Prim’s algorithm using greedy techniques
in C.
Algorithm:
1. Start the Program.
2. Type the codings in Turbo C.
3. Read number of array elements n.
4. Define array elements Ai, i = 0,1,2,…n–1.
5. Use if..else statement to check the conditions.
6. Compile the program filename.cpp.
7. Run the program.
8. Save the program with extension .cpp.
9. Stop the program.
33 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include <stdio.h>
#include <limits.h>
#define vertices 5
int minimum_key(int k[], int mst[])
{
int minimum = INT_MAX, min,i;
for (i = 0; i < vertices; i++)
if (mst[i] == 0 && k[i] < minimum )
minimum = k[i], min = i;
return min;
}
void prim(int g[vertices][vertices])
{
int parent[vertices];
int k[vertices];
int mst[vertices];
int i, count,edge,v;
for (i = 0; i < vertices; i++)
{
k[i] = INT_MAX;
mst[i] = 0;
}
k[0] = 0;
parent[0] = -1;
for (count = 0; count < vertices-1; count++)
{
edge = minimum_key(k, mst);
mst[edge] = 1;
for (v = 0; v < vertices; v++)
{
if (g[edge][v] && mst[v] == 0 && g[edge][v] < k[v])
{
parent[v] = edge, k[v] = g[edge][v];
}
}
}
printf("\n Edge \t Weight\n");
for (i = 1; i < vertices; i++)
printf(" %d <-> %d %d \n", parent[i], i, g[i][parent[i]]);
}
int main()
{
34 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
int g[vertices][vertices] = {{0, 0, 3, 0, 0},
{0, 0, 10, 4, 0},
{3, 10, 0, 2, 6},
{0, 4, 2, 0, 1},
{0, 0, 6, 1, 0},
};
prim(g);
return 0;
}
Output:
Edge Weight
3 <-> 1 4
0 <-> 2 3
2 <-> 3 2
3 <-> 4 1
Result:
Thus the program has been successfully obtained and the output is verified.
35 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Ex no:09
Implementation of n-queen problem using
backtracking
Aim:
To write a program for the implementation of N-queen problem using backtracking in C.
Algorithm:
1. Start the Program.
2. Type the codings in Turbo C.
3. Read number of array elements n.
4. Define array elements Ai, i = 0,1,2,…n–1.
5. Use if..else statement to check the conditions.
6. Compile the program filename.cpp.
7. Run the program.
8. Save the program with extension .cpp.
9. Stop the program.
36 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Source code:
#include<stdio.h>
#include<math.h>
int board[20],count;
int main()
{
int n,i,j;
void queen(int row,int n);
printf(" - N Queens Problem Using Backtracking -");
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}
void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);
for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
for(j=1;j<=n;++j)
{
if(board[i]==j)
printf("\tQ");
else
printf("\t-");
}
}
}
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++i)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
37 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
return 0;
}
return 1;
}
void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column;
if(row==n)
print(n);
else
queen(row+1,n);
}
}
}
38 SACWC
DATA STRUCTURES& ALGORITHMS LAB November 2024
Output:
N Queens Problem Using Backtracking
Enter number of Queens: 4
Solution 1:
1 2 3 4
1 - Q - -
2 - - - Q
3 Q - - -
4 - - Q -
Solution 2:
1 2 3 4
1 - - Q -
2 Q - - -
3 - - - Q
4 - Q - -
Result:
Thus the program has been successfully obtained and the output is verified.
39 SACWC