0% found this document useful (0 votes)
22 views

Lab 1-1

Lab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lab 1-1

Lab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

8))From a given vertex in a weighted connected graph, find shortest

paths from 0 to
other vertices using Dijkstra’s algorithm and output its time
complexity.

#include <stdio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX], int n, int startnode);

int main() {
int G[MAX][MAX], i, j, n, u;

printf("\nEnter the number of vertices (max %d): ", MAX);


scanf("%d", &n);

if (n > MAX || n <= 0) {


printf("Invalid number of vertices.\n");
return 1;
}

printf("\nEnter the adjacency matrix:\n");


for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &G[i][j]);
if (G[i][j] < 0) {
printf("Invalid entry in adjacency matrix. Weight cannot be negative.\n");
return 1;
}
}
}

printf("\nEnter the starting node: ");


scanf("%d", &u);

if (u < 0 || u >= n) {
printf("Invalid starting node.\n");
return 1;
}

dijkstra(G, n, u);

return 0;
}

void dijkstra(int G[MAX][MAX], int n, int startnode) {


int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX], count, mindistance, nextnode, i, j;

// Creating the cost matrix


for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(G[i][j] == 0 && i != j)
cost[i][j] = INFINITY;
else
cost[i][j] = G[i][j];
}
}

// Initializing arrays
for(i = 0; i < n; i++) {
distance[i] = cost[startnode][i];
pred[i] = startnode;
visited[i] = 0;
}

distance[startnode] = 0;
visited[startnode] = 1;
count = 1;

// Dijkstra's algorithm
while(count < n - 1) {
mindistance = INFINITY;

// Finding the next node


for(i = 0; i < n; i++)
if(distance[i] < mindistance && !visited[i]) {
mindistance = distance[i];
nextnode = i;
}

visited[nextnode] = 1;

// Updating the distances


for(i = 0; i < n; i++)
if(!visited[i])
if(mindistance + cost[nextnode][i] < distance[i]) {
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode;
}
count++;
}

// Printing the results


for(i = 0; i < n; i++) {
if(i != startnode) {
printf("\nDistance of node %d = %d", i, distance[i]);
printf("\nPath = %d", i);

j = i;
do {
j = pred[j];
printf(" <- %d", j);
} while(j != startnode);
}
}
}
Output
Enter the number of vertices (max 10): 4

Enter the adjacency matrix:


0 10 15 0
10 0 35 25
15 35 0 30
0 25 30 0

Enter the starting node: 0

Distance of node 1 = 10
Path = 1 <- 0

Distance of node 2 = 15
Path = 2 <- 0

Distance of node 3 = 35
Path = 3 <- 1 <- 0

9))Find Minimum Cost Spanning Tree of a given undirected graph


using Kruskal’s
algorithm and output its time complexity

#include <stdio.h>
#include <stdlib.h>

int i, j, k, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[9][9], parent[9];

int find(int i);


int uni(int i, int j);

int main() {
printf("\n\tImplementation of Kruskal's algorithm\n");
printf("\nEnter the number of vertices: ");
scanf("%d", &n);

printf("\nEnter the cost adjacency matrix:\n");


for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
scanf("%d", &cost[i][j]);
if(cost[i][j] == 0)
cost[i][j] = 999; // Use a large number to represent infinity
}
}

printf("The edges of Minimum Cost Spanning Tree are:\n");


while(ne < n) {
for(i = 1, min = 999; i <= n; i++) {
for(j = 1; j <= n; j++) {
if(cost[i][j] < min) {
min = cost[i][j];
a = u = i;
b = v = j;
}
}
}

u = find(u);
v = find(v);

if(uni(u, v)) {
printf("%d edge (%d,%d) = %d\n", ne++, a, b, min);
mincost += min;
}
cost[a][b] = cost[b][a] = 999;
}

printf("\n\tMinimum cost = %d\n", mincost);

// Output the time complexity of Kruskal's algorithm


printf("\nTime Complexity: O(E log E)\n");

return 0;
}

int find(int i) {
while(parent[i])
i = parent[i];
return i;
}
int uni(int i, int j) {
if(i != j) {
parent[j] = i;
return 1;
}
return 0;
}

Output
Implementation of Kruskal's algorithm

Enter the number of vertices: 4

Enter the cost adjacency matrix:


0 10 15 20
10 0 35 25
15 35 0 30
20 25 30 0
The edges of Minimum Cost Spanning Tree are:
1 edge (1,2) = 10
2 edge (1,3) = 15
3 edge (2,4) = 25

Minimum cost = 50

Time Complexity: O(E log E)


10))Perform various non-recursive tree traversal algorithms for a given binary
tree
and output its time complexity

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node *left, *right;
} Node;

// Queue structure for Level Order Traversal


typedef struct Queue {
Node* data;
struct Queue* next;
} Queue;

// Stack structure for Inorder, Preorder, Postorder Traversal


typedef struct Stack {
Node* data;
struct Stack* next;
} Stack;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

void push(Stack** top, Node* node) {


Stack* newStack = (Stack*)malloc(sizeof(Stack));
newStack->data = node;
newStack->next = *top;
*top = newStack;
}

Node* pop(Stack** top) {


if (*top == NULL) return NULL;
Stack* temp = *top;
*top = (*top)->next;
Node* node = temp->data;
free(temp);
return node;
}

void enqueue(Queue** front, Queue** rear, Node* node) {


Queue* newQueue = (Queue*)malloc(sizeof(Queue));
newQueue->data = node;
newQueue->next = NULL;
if (*rear == NULL) {
*front = *rear = newQueue;
return;
}
(*rear)->next = newQueue;
*rear = newQueue;
}

Node* dequeue(Queue** front) {


if (*front == NULL) return NULL;
Queue* temp = *front;
*front = (*front)->next;
Node* node = temp->data;
free(temp);
return node;
}

void inorder(Node* root) {


Stack* stack = NULL;
Node* current = root;
printf("Inorder Traversal: ");

while (current != NULL || stack != NULL) {


while (current != NULL) {
push(&stack, current);
current = current->left;
}
current = pop(&stack);
printf("%d ", current->data);
current = current->right;
}
printf("\n");
}

void preorder(Node* root) {


Stack* stack = NULL;
printf("Preorder Traversal: ");
push(&stack, root);

while (stack != NULL) {


Node* node = pop(&stack);
printf("%d ", node->data);
if (node->right) push(&stack, node->right);
if (node->left) push(&stack, node->left);
}
printf("\n");
}

void postorder(Node* root) {


Stack *stack1 = NULL, *stack2 = NULL;
printf("Postorder Traversal: ");
push(&stack1, root);

while (stack1 != NULL) {


Node* node = pop(&stack1);
push(&stack2, node);
if (node->left) push(&stack1, node->left);
if (node->right) push(&stack1, node->right);
}

while (stack2 != NULL) {


Node* node = pop(&stack2);
printf("%d ", node->data);
}
printf("\n");
}

void levelOrder(Node* root) {


Queue* front = NULL;
Queue* rear = NULL;
printf("Level Order Traversal: ");
enqueue(&front, &rear, root);

while (front != NULL) {


Node* node = dequeue(&front);
printf("%d ", node->data);
if (node->left) enqueue(&front, &rear, node->left);
if (node->right) enqueue(&front, &rear, node->right);
}
printf("\n");
}

int main() {
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
inorder(root);
preorder(root);
postorder(root);
levelOrder(root);

// Output time complexities


printf("\nTime Complexity for Inorder, Preorder, Postorder
Traversals: O(n)\n");
printf("Time Complexity for Level Order Traversal: O(n)\n");

return 0;
}

Output

Inorder Traversal: 4 2 5 1 6 3 7
Preorder Traversal: 1 2 4 5 3 6 7
Postorder Traversal: 4 5 2 6 7 3 1
Level Order Traversal: 1 2 3 4 5 6 7
Time Complexity for Inorder, Preorder, Postorder Traversals: O(n)
Time Complexity for Level Order Traversal: O(n)
12))Find a subset of a given set S = { sl, s2, ……,sn } of n positive
integers whose
sum is equal to a given positive integer d and output its time
complexity.
For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions {1,
2, 6} and
{1,8}. A suitable message is to be displayed if the given problem
instance
doesn't have a solution

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define MAX 100

void printSubset(int set[], bool dp[MAX][MAX], int i, int j) {


if (j == 0) {
return;
}

if (i == 0) {
if (dp[i][j]) {
printf("%d ", set[i]);
}
return;
}

if (dp[i][j] && !dp[i-1][j]) {


printSubset(set, dp, i-1, j - set[i]);
printf("%d ", set[i]);
} else {
printSubset(set, dp, i-1, j);
}
}

void subsetSum(int set[], int n, int d) {


bool dp[MAX][MAX] = {false}; // Initialize dp table to false
int i, j;

if (d >= MAX) {
printf("Desired sum exceeds maximum allowed value.\n");
return;
}

// Initialize the dp table


for (i = 0; i <= n; i++) {
for (j = 0; j <= d; j++) {
if (j == 0)
dp[i][j] = true;
else if (i == 0)
dp[i][j] = false;
else if (set[i-1] <= j)
dp[i][j] = dp[i-1][j] || dp[i-1][j - set[i-1]];
else
dp[i][j] = dp[i-1][j];
}
}

// Print the result


if (!dp[n][d]) {
printf("No subset with sum %d\n", d);
} else {
printf("Subset with sum %d: ", d);
printSubset(set, dp, n-1, d);
printf("\n");
}
}

int main() {
int set[MAX], n, d;
int i;

// Read the number of elements


printf("Enter the number of elements in the set: ");
scanf("%d", &n);
if (n <= 0 || n > MAX) {
printf("Invalid number of elements.\n");
return 1;
}

// Read the elements of the set


printf("Enter the elements of the set:\n");
for (i = 0; i < n; i++) {
scanf("%d", &set[i]);
if (set[i] < 0) {
printf("Elements must be positive integers.\n");
return 1;
}
}

// Read the target sum


printf("Enter the target sum: ");
scanf("%d", &d);

if (d < 0) {
printf("The target sum must be a positive integer.\n");
return 1;
}

// Call the subset sum function


subsetSum(set, n, d);

return 0;
}

Output

Enter the number of elements in the set: 4


Enter the elements of the set: 1 2 3 4
Enter the target sum: 15
No subset with sum 15
13))Implement any scheme to find the optimal solution for the Travelling Sales
Person problem and output its time complexity

#include <stdio.h>
#include <limits.h>

#define MAX 20
#define INF 1000000

int dist[MAX][MAX];
int dp[1 << MAX][MAX];
int n;

// Function to find the minimum cost path


int tsp(int mask, int pos) {
if (mask == (1 << n) - 1) {
return dist[pos][0];
}

if (dp[mask][pos] != -1) {
return dp[mask][pos];
}

int ans = INF;


for (int city = 0; city < n; city++) {
if ((mask & (1 << city)) == 0) {
int newAns = dist[pos][city] + tsp(mask | (1 << city), city);
if (newAns < ans) {
ans = newAns;
}
}
}

return dp[mask][pos] = ans;


}

int main() {
printf("Enter the number of cities: ");
scanf("%d", &n);

printf("Enter the distance matrix:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &dist[i][j]);
}
}

// Initialize dp table with -1


for (int i = 0; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
dp[i][j] = -1;
}
}

int result = tsp(1, 0); // Start from the first city with only the first city visited
printf("Minimum cost: %d\n", result);

return 0;
}

Output
Enter the number of cities: 4
Enter the distance matrix: 0 1 2 9
1 0 6 4
2 6 0 3
9 4 3 0
Minimum cost: 13
14))Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm and output its time complexity.

#include <stdio.h>
#include <limits.h>

#define MAX 100


#define INF INT_MAX

void prim(int graph[MAX][MAX], int n);

int main() {
int graph[MAX][MAX], n, i, j;

// Read the number of vertices


printf("Enter the number of vertices: ");
scanf("%d", &n);

// Read the adjacency matrix


printf("Enter the adjacency matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
if (graph[i][j] < 0) {
printf("Invalid entry. Weights must be non-negative.\n");
return 1;
}
}
}

// Call Prim's algorithm


prim(graph, n);

return 0;
}

void prim(int graph[MAX][MAX], int n) {


int parent[MAX]; // Array to store the MST
int key[MAX]; // Key values to pick minimum weight edge
int mstSet[MAX]; // To check if the vertex is included in MST
int i, j;

// Initialize all keys as INF


for (i = 0; i < n; i++) {
key[i] = INF;
mstSet[i] = 0;
}

// Always include the first vertex in the MST


key[0] = 0; // Make key 0 so that this vertex is picked as the first vertex
parent[0] = -1; // First node is always root of MST

for (i = 0; i < n - 1; i++) {


// Find the vertex with the minimum key value
int min = INF, min_index;
for (j = 0; j < n; j++) {
if (!mstSet[j] && key[j] < min) {
min = key[j];
min_index = j;
}
}

// Add the selected vertex to the MST set


int u = min_index;
mstSet[u] = 1;

// Update key value of the adjacent vertices of the selected vertex


for (j = 0; j < n; j++) {
if (graph[u][j] && !mstSet[j] && graph[u][j] < key[j]) {
key[j] = graph[u][j];
parent[j] = u;
}
}
}

// Print the MST


printf("Edge \tWeight\n");
int minCost = 0;
for (i = 1; i < n; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
minCost += graph[i][parent[i]];
}
printf("Minimum Cost of Spanning Tree: %d\n", minCost);
}
Output

Enter the number of vertices: 5


Enter the adjacency matrix: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
Output
Edge Weight
0-1 2
1-2 3
1-4 5
0-3 6
Minimum Cost of Spanning Tree: 16
15)))Implement All-Pairs Shortest Paths Problem using Floyd's algorithm and output
its time complexity.

#include <stdio.h>
#include <limits.h>

#define MAX 100


#define INF INT_MAX

void floydWarshall(int graph[MAX][MAX], int n) {


int dist[MAX][MAX];
int i, j, k;

// Initialize the distance matrix with the given graph's weights


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i == j) {
dist[i][j] = 0;
} else if (graph[i][j] == 0) {
dist[i][j] = INF;
} else {
dist[i][j] = graph[i][j];
}
}
}

// Floyd-Warshall Algorithm
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (dist[i][k] != INF && dist[k][j] != INF &&
dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

// Print the result


printf("Shortest distances between every pair of vertices:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (dist[i][j] == INF) {
printf("INF\t");
} else {
printf("%d\t", dist[i][j]);
}
}
printf("\n");
}
}

int main() {
int graph[MAX][MAX], n, i, j;

// Read the number of vertices


printf("Enter the number of vertices: ");
scanf("%d", &n);

// Read the adjacency matrix


printf("Enter the adjacency matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
if (graph[i][j] < 0 && i != j) {
printf("Invalid entry. Weights must be non-negative or zero.\n");
return 1;
}
}
}

// Call Floyd-Warshall algorithm


floydWarshall(graph, n);

return 0;
}

Output
Enter the number of vertices: 3
Enter the adjacency matrix:
014
102
420
Shortest distances between every pair of vertices:
0 1 3
1 0 2
3 2 0
16)))Implement N Queen's problem using Back Tracking and output its time
complexity

#include <stdio.h>
#include <stdbool.h>

#define MAX 20

int board[MAX][MAX];
int N;

// Function to print the board


void printBoard() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1) {
printf("Q ");
} else {
printf(". ");
}
}
printf("\n");
}
printf("\n");
}

// Function to check if a queen can be placed at board[row][col]


bool isSafe(int row, int col) {
int i, j;

// Check this row on the left side


for (i = 0; i < col; i++) {
if (board[row][i]) {
return false;
}
}

// Check upper diagonal on the left side


for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j]) {
return false;
}
}

// Check lower diagonal on the left side


for (i = row, j = col; j >= 0 && i < N; i++, j--) {
if (board[i][j]) {
return false;
}
}

return true;
}

// Recursive function to solve N-Queens problem


bool solveNQueens(int col) {
if (col >= N) {
return true;
}

for (int row = 0; row < N; row++) {


if (isSafe(row, col)) {
board[row][col] = 1; // Place queen
if (solveNQueens(col + 1)) {
return true;
}
board[row][col] = 0; // Remove queen (backtrack)
}
}

return false;
}

int main() {
printf("Enter the number of queens (N): ");
scanf("%d", &N);

if (N <= 0 || N > MAX) {


printf("Invalid number of queens.\n");
return 1;
}

// Initialize the board


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
board[i][j] = 0;
}
}

if (solveNQueens(0)) {
printf("Solution to %d-Queens problem:\n", N);
printBoard();
} else {
printf("No solution exists for %d-Queens problem.\n", N);
}

return 0;
}

Output

Enter the number of queens (N): 4


Solution to 4-Queens problem:
.Q..
...Q
Q...
..Q.

You might also like