0% found this document useful (0 votes)
25 views37 pages

AoA Exp 1 To 10 by Gaurav Ameta

Uploaded by

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

AoA Exp 1 To 10 by Gaurav Ameta

Uploaded by

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

Experiment – 1

Aim:- Sort a given set of elements using the Quicksort method and determine
the time required to sort the elements. Repeat the experiment for different
values of n, the number of elements in the list to be sorted and plot a graph
of the time taken versus n. The elements can be read from a file or can be
generated using the random number generator.
Program :-
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to swap two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Partition function for Quicksort
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Last element as pivot
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
// Quicksort function
void quicksort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
// Function to generate random array
void generate_random_array(int arr[], int n) {
for (int i = 0; i < n; i++) {
arr[i] = rand() % 10000; // Random numbers between 0 and 9999
}
}
// Main function
int main() {
int sizes[] = {100, 500, 1000, 5000, 10000}; // Sizes for the experiment
int num_sizes = sizeof(sizes) / sizeof(sizes[0]);
printf("Size\tTime (seconds)\tSorted Values (First 10)\n");
printf("---------------------------------------------------\n");
for (int i = 0; i < num_sizes; i++) {
int n = sizes[i];
int *arr = (int *)malloc(n * sizeof(int));
// Generate random array
generate_random_array(arr, n);
// Measure sorting time
clock_t start = clock();
quicksort(arr, 0, n - 1);
clock_t end = clock();
double time_taken = (double)(end - start) / CLOCKS_PER_SEC;
// Print size, time taken, and first 10 sorted values
printf("%d\t%.6f\t\t", n, time_taken);
for (int j = 0; j < (n < 10 ? n : 10); j++) { // Print first 10 or all values if n <
printf("%d ", arr[j]);
}
printf("\n");
free(arr); // Free allocated memory
}
return 0;
}
Output:-
Size Time (seconds) Sorted Values (First 10)
---------------------------------------------------
100 0.000009 12 27 59 336 364 492 540 545 846 886
500 0.000041 19 28 49 71 81 84 90 97 124 163
1000 0.000094 0 3 8 19 30 30 32 37 49 49
5000 0.000530 1 1 5 5 10 12 12 14 17 18
10000 0.000941 1 4 5 6 8 8 10 11 12 13
Experiment – 2
Aim :- Implement a parallelized Merge Sort algorithm to sort a given set of
elements and determine the time required to sort the elements. Repeat the
experiment for different values of n, the number of elements in the list to be
sorted and plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.
Program:-
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Merge two sorted halves
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int *L = (int *)malloc(n1 * sizeof(int));
int *R = (int *)malloc(n2 * sizeof(int));
for (int i = 0; i < n1; i++) L[i] = arr[left + i];
for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];

free(L);
free(R);
}
// Sequential Merge Sort
void merge_sort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
merge_sort(arr, left, mid);
merge_sort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
// Generate random array
void generate_random_array(int arr[], int n) {
for (int i = 0; i < n; i++) {
arr[i] = rand() % 100000; // Random numbers between 0 and 99999
}
}
// Main function
int main() {
int sizes[] = {100, 500, 1000, 5000, 10000}; // Array sizes
int num_sizes = sizeof(sizes) / sizeof(sizes[0]);
printf("Size\tTime (seconds)\tSorted Values (First 10)\n");
printf("-----------------------------------------------------------\n");
for (int i = 0; i < num_sizes; i++) {
int n = sizes[i];
int *arr = (int *)malloc(n * sizeof(int));
generate_random_array(arr, n);
// Measure sorting time
clock_t start = clock();
merge_sort(arr, 0, n - 1);
clock_t end = clock();
double time_taken = (double)(end - start) / CLOCKS_PER_SEC;
// Print size, time taken, and first 10 sorted values
printf("%d\t%.6f\t\t", n, time_taken);
for (int j = 0; j < (n < 10 ? n : 10); j++)
{ // Print first 10 or all values if n < 10
printf("%d ", arr[j]);
}
printf("\n");
free(arr);
}
return 0;
}
Output:-
Size Time (seconds) Sorted Values (First 10)
-----------------------------------------------------------
100 0.000016 545 2305 2362 2567 2651 3135 3526 5211 5403 6862
500 0.000089 81 237 569 606 681 723 973 1039 1255 1474
1000 0.000166 30 346 657 669 801 821 925 938 960 1052
5000 0.000955 10 34 44 77 93 96 113 117 131 178
10000 0.001874 4 13 14 29 44 64 154 158 161 168
Experiment – 3
Aim :- (A) Obtain the Topological ordering of vertices in a given digraph.
(B) Compute the transitive closure of a given directed graph using Warshall's
algorithm.
Program :-
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX 100

// Stack for Topological Sorting


int stack[MAX];
int top = -1;

void push(int v) {
stack[++top] = v;
}

int pop() {
return stack[top--];
}

// DFS for Topological Sorting


void dfs_topological(int v, bool visited[], int adj[MAX][MAX], int n) {
visited[v] = true;

for (int i = 0; i < n; i++) {


if (adj[v][i] && !visited[i]) {
dfs_topological(i, visited, adj, n);
}
}

push(v);
}

// Function to find Topological Order


void topological_sort(int adj[MAX][MAX], int n) {
bool visited[MAX] = {false};

for (int i = 0; i < n; i++) {


if (!visited[i]) {
dfs_topological(i, visited, adj, n);
}
}

printf("Topological Order: ");


while (top != -1) {
printf("%d ", pop());
}
printf("\n");
}

// Function to compute Transitive Closure using Warshall's Algorithm


void transitive_closure(int adj[MAX][MAX], int n) {
int closure[MAX][MAX];

// Initialize closure matrix


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
closure[i][j] = adj[i][j];
}
}

// Apply Warshall's algorithm


for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
closure[i][j] = closure[i][j] || (closure[i][k] && closure[k][j]);
}
}
}

// Print Transitive Closure


printf("Transitive Closure:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", closure[i][j]);
}
printf("\n");
}
}
int main() {
int n, choice;
int adj[MAX][MAX];

printf("Enter the number of vertices in the graph: ");


scanf("%d", &n);

printf("Enter the adjacency matrix (%dx%d):\n", n, n);


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

while (1) {
printf("\nMenu:\n");
printf("1. Find Topological Ordering\n");
printf("2. Compute Transitive Closure\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
topological_sort(adj, n);
break;
case 2:
transitive_closure(adj, n);
break;
case 3:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}
Output:-
Enter the number of vertices in the graph: 4
Enter the adjacency matrix (4x4):
1000
0010
0100
0001

Menu:
1. Find Topological Ordering
2. Compute Transitive Closure
3. Exit
Enter your choice: 1
Topological Order: 3 1 2 0
Menu:
1. Find Topological Ordering
2. Compute Transitive Closure
3. Exit
Enter your choice: 2
Transitive Closure:
1000
0110
0110
0001

Menu:
1. Find Topological Ordering
2. Compute Transitive Closure
3. Exit
Enter your choice: 3
Experiment – 4
Aim :- Implement 0/1 Knapsack problem using Dynamic Programming.

Program:-
#include<stdio.h>
void knapsack01(int v[],int w[],int n,int capacity)
{
int x=0,b[100][100],i=0;
for(x=0;x<=capacity;x++)
b[0][x]=0;
for(i=1;i<=n;i++)
b[i][0]=0;
for(i=1;i<=n;i++)
{
for(x=1;x<=capacity;x++)
{
if(w[i]<=x)
{
if( (v[i]+b[i-1][x-w[i]] ) > b[i-1][x] )
b[i][x]= (v[i]+b[i-1][x-w[i]] ) ;
else
b[i][x]=b[i-1][x];
}
else
b[i][x]=b[i-1][x];
}
}
printf("the matix is\n");
for(i=0;i<=n;i++)
{
for(x=0;x<=capacity;x++)
printf("\t%d",b[i][x]);
printf("\n");
}
printf("the benifits is \n%d",b[n][capacity]);
printf("\nthe selected items is\n");
i=n,x=capacity;
while(i>0 && x>0)
{
if(b[i][x]!=b[i-1][x])
{
printf("\t%d",i);
b[i][x]=b[i-1][x-w[i]];
x=x-w[i];
i=i-1;
}
else
{
b[i][x]=b[i-1][x];
i=i-1;
}
}
}
void main()
{
int i,n,capacity,v[100],w[100];
printf("enter the total capacity of knapsack \n");
scanf("%d",&capacity);
printf("enter the no of items\n");
scanf("%d",&n);//value of each item's
printf("enter the weight and value of items\n");
for(i=1;i<=n;i++)
scanf("%d %d",&w[i],&v[i]);
knapsack01(v,w,n,capacity);
}

Output:-
enter the total capacity of knapsack
50
enter the no of items
3
enter the weight and value of items
10 60
20 100
30 120
the matix is

0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0

0 0 0 0 0 0 0 0 0 0 60 60 60
60 60 60 60 60 60 60 60 60 60 60 60
60 60 60 60 60 60 60 60 60 60 60 60
60 60 60 60 60 60 60 60 60 60 60 60
60 60

0 0 0 0 0 0 0 0 0 0 60 60 60
60 60 60 60 60 60 60 100 100 100 100
100 100 100 100 100 100 160 160 160 160 160
160 160 160 160 160 160 160 160 160 160 160
160 160 160 160 160

0 0 0 0 0 0 0 0 0 0 60 60 60
60 60 60 60 60 60 60 100 100 100 100
100 100 100 100 100 100 160 160 160 160 160
160 160 160 160 160 180 180 180 180 180 180
180 180 180 180 220
the benifits is
220
the selected items is
3 2
Experiment – 5
Aim :- From a given vertex in a weighted connected graph, find shortest
paths to other vertices using Dijkstra's algorithm.
Program :-
#include <stdio.h>
#include <limits.h>

#define MAX 100


#define INF INT_MAX

// Function to find the vertex with the minimum distance value


int min_distance(int dist[], int sptSet[], int n) {
int min = INF, min_index;

for (int v = 0; v < n; v++) {


if (sptSet[v] == 0 && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}

// Function to implement Dijkstra's algorithm


void dijkstra(int graph[MAX][MAX], int n, int src) {
int dist[MAX]; // The array to hold the shortest distance from src
int sptSet[MAX]; // Shortest Path Tree Set (to track vertices for which the
shortest distance is finalized)
int parent[MAX]; // Array to store the path

// Initialize all distances as infinity and sptSet[] as false (0)


for (int i = 0; i < n; i++) {
dist[i] = INF;
sptSet[i] = 0;
parent[i] = -1; // No parent initially
}
dist[src] = 0; // Distance to the source is always 0

// Find the shortest path for all vertices


for (int count = 0; count < n - 1; count++) {
// Pick the minimum distance vertex from the set of vertices not yet
processed
int u = min_distance(dist, sptSet, n);

// Mark the picked vertex as processed


sptSet[u] = 1;

// Update the distance value of the adjacent vertices of the picked vertex
for (int v = 0; v < n; v++) {
// Update dist[v] if there is a shorter path from u to v
if (sptSet[v] == 0 && graph[u][v] && dist[u] != INF && dist[u] +
graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
parent[v] = u; // Update the parent of v
}
}
}

// Print the graph as a line diagram


printf("\nGraph Representation (Adjacency Matrix):\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", graph[i][j]);
}
printf("\n");
}

// Print the shortest distances from the source


printf("\nShortest Distances from Source Vertex %d:\n", src);
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < n; i++) {
if (dist[i] == INF) {
printf("%d \t INF\n", i);
} else {
printf("%d \t %d\n", i, dist[i]);
}
}

// Line Diagram of the Shortest Path Tree


printf("\nLine Diagram Representation of Shortest Path Tree:\n");
for (int i = 0; i < n; i++) {
if (dist[i] != INF && i != src) {
int current = i;
printf("Vertex %d: ", i);
// Backtrack to find the path from source to the current vertex
while (parent[current] != -1) {
printf("%d <- ", current);
current = parent[current];
}
printf("%d\n", src);
}
}
}

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

// Take input for number of vertices and the adjacency matrix


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

printf("Enter the adjacency matrix (Enter 0 if there is no edge between


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

// Take input for the source vertex


printf("Enter the source vertex: ");
scanf("%d", &src);

// Call Dijkstra's algorithm


dijkstra(graph, n, src);
return 0;
}
Output:-
Enter the number of vertices: 5
Enter the adjacency matrix (Enter 0 if there is no edge between vertices):
0 10 0 0 5
0 0 0 10 0
00000
00000
00050
Enter the source vertex: 0

Graph Representation (Adjacency Matrix):


0 10 0 0 5
0 0 0 10 0
00000
00000
00050

Shortest Distances from Source Vertex 0:


Vertex Distance from Source
0 0
1 10
2 INF
3 10
4 5

Line Diagram Representation of Shortest Path Tree:


Vertex 1: 1 <- 0
Vertex 3: 3 <- 4 <- 0
Vertex 4: 4 <- 0
Experiment – 6
Aim :- Find Minimum Cost Spanning Tree of a given undirected graph using
Kruskal's algorithm.
Program:-
#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);
int uni(int, int);

void main() {
printf("\n\n\tImplementation of Kruskal's Algorithm\n\n");

printf("Enter the number of vertices: ");


scanf("%d", &n);

printf("Enter 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; // No edge between i and j
}
}
}

// Kruskal's algorithm starts here


printf("\nThe edges of Minimum Cost Spanning Tree are:\n\n");
while(ne < n) {
min = 999;

// Find the minimum cost edge


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

// Check if adding this edge forms a cycle


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

// If it doesn't form a cycle, include it in the MST


if(uni(u, v)) {
printf("Edge (%d,%d) = %d\n", a, b, min);
mincost += min;
ne++;
}

// Remove the selected edge from the graph (set its cost to 999)
cost[a][b] = cost[b][a] = 999;
}

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


}

int find(int i) {
while(parent[i]) {
i = parent[i];
}
return i;
}

int uni(int i, int j) {


if(i != j) {
parent[j] = i; // Union of sets
return 1;
}
return 0;
}
Output:-
Enter the number of vertices: 4
Enter the cost adjacency matrix:
0 10 20 30
10 0 40 60
20 40 0 50
30 50 60 0

The edges of Minimum Cost Spanning Tree are:

Edge (1,2) = 10
Edge (1,3) = 20
Edge (1,4) = 30

Minimum cost = 60
Experiment – 7
Aim :- (A) Print all the nodes reachable from a given starting node in a
digraph using BFS method. (B) Check whether a given graph is connected
or not using DFS method.
Program:-
#include<stdio.h>
#include<stdlib.h>

#define MAX 20

int graph[MAX][MAX], visited[MAX], n;

void BFS(int start) {


int queue[MAX], front = -1, rear = -1;
visited[start] = 1;
queue[++rear] = start;

printf("Nodes reachable from node %d using BFS: ", start);


while (front < rear) {
int node = queue[++front];
printf("%d ", node);

// Traverse the neighbors of the current node


for (int i = 0; i < n; i++) {
if (graph[node][i] == 1 && !visited[i]) {
visited[i] = 1;
queue[++rear] = i;
}
}
}
printf("\n");
}

void DFS(int node) {


printf("%d ", node);
visited[node] = 1;

// Visit all the neighbors of the node


for (int i = 0; i < n; i++) {
if (graph[node][i] == 1 && !visited[i]) {
DFS(i);
}
}
}

int isConnected() {
// Start DFS from node 0
for (int i = 0; i < n; i++) visited[i] = 0; // Reset visited array
DFS(0);

// Check if all nodes were visited (graph is connected if all nodes are visited)
for (int i = 0; i < n; i++) {
if (!visited[i]) {
return 0; // Graph is not connected
}
}
return 1; // Graph is connected
}

void menu() {
int startNode, choice;

do {
printf("\n--- Menu ---\n");
printf("1. BFS to print reachable nodes from a given start node\n");
printf("2. Check if the graph is connected using DFS\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the starting node for BFS: ");
scanf("%d", &startNode);
for (int i = 0; i < n; i++) visited[i] = 0; // Reset visited array
BFS(startNode);
break;
case 2:
if (isConnected()) {
printf("The graph is connected.\n");
} else {
printf("The graph is not connected.\n");
}
break;

case 3:
printf("Exiting the program.\n");
break;

default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 3); // Loop until user chooses to exit
}

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

// Initialize the adjacency matrix


printf("Enter the adjacency matrix (0 for no edge, 1 for an edge):\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}

// Display menu
menu();

return 0;
}
Output:-
Enter the number of nodes in the graph: 4
Enter the adjacency matrix (0 for no edge, 1 for an edge):
0101
1010
0101
1010

--- Menu ---


1. BFS to print reachable nodes from a given start node
2. Check if the graph is connected using DFS
3. Exit
Enter your choice: 1
Enter the starting node for BFS: 0
Nodes reachable from node 0 using BFS: 0 1 3 2

--- Menu ---


1. BFS to print reachable nodes from a given start node
2. Check if the graph is connected using DFS
3. Exit
Enter your choice: 2
0 1 2 3 The graph is connected.

--- Menu ---


1. BFS to print reachable nodes from a given start node
2. Check if the graph is connected using DFS
3. Exit
Enter your choice: 3
Exiting the program.
Experiment – 8
Aim :- Find Minimum Cost Spanning Tree of a given undirected graph
using Prim’s algorithm.
Program:-
#include <stdio.h>
#include <limits.h>

#define MAX 20

int graph[MAX][MAX], n;

void primsAlgorithm() {
int parent[MAX], key[MAX], visited[MAX];
int minCost = 0;

// Initialize the arrays


for (int i = 0; i < n; i++) {
key[i] = INT_MAX; // Key values used to pick the minimum weight edge
visited[i] = 0; // Keep track of vertices included in MST
parent[i] = -1; // Array to store the constructed MST
}

// Start with the first vertex (0th index)


key[0] = 0;

// Loop until all vertices are included in the MST


for (int count = 0; count < n - 1; count++) {
// Find the vertex with the minimum key value
int u = -1, min = INT_MAX;
for (int i = 0; i < n; i++) {
if (!visited[i] && key[i] < min) {
min = key[i];
u = i;
}
}

// Mark the chosen vertex as visited


visited[u] = 1;

// Add the weight of the edge to the minimum cost


minCost += min;

// Update the key values of the adjacent vertices


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

// Output the Minimum Cost Spanning Tree


printf("\nEdges in the Minimum Cost Spanning Tree (MST):\n");
for (int i = 1; i < n; i++) {
printf("%d - %d (Weight: %d)\n", parent[i], i, graph[i][parent[i]]);
}

printf("\nMinimum cost of the spanning tree: %d\n", minCost);


}

int main() {
// Input the number of vertices in the graph
printf("Enter the number of vertices: ");
scanf("%d", &n);

// Input the adjacency matrix (weights of edges)


printf("Enter the adjacency matrix (0 for no edge, else enter weight):\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}

// Call the Prim's algorithm to find MST


primsAlgorithm();

return 0;
}
Output:-
Enter the number of vertices: 5
Enter the adjacency matrix (0 for no edge, else enter weight):
02060
20385
03007
68090
05700

Edges in the Minimum Cost Spanning Tree (MST):


0 - 1 (Weight: 2)
1 - 2 (Weight: 3)
0 - 3 (Weight: 6)
1 - 4 (Weight: 5)

Minimum cost of the spanning tree: 10


Experiment – 9
Aim :- Implement All-Pairs Shortest Paths Problem using Floyd's algorithm.
Program:-
#include <stdio.h>
#include <limits.h>

#define MAX 10
#define INF INT_MAX

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


// dist[][] will be the output matrix that will have the shortest distances
int dist[MAX][MAX], i, j, k;

// Initialize the distance matrix with the input graph


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; // No direct edge between i and j
} else {
dist[i][j] = graph[i][j]; // Edge weight between i and j
}
}
}

// Floyd-Warshall algorithm to find shortest paths


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]; // Update the shortest path
}
}
}
}
// Output the shortest path matrix
printf("\nShortest 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;

// Input number of vertices


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

// Input the adjacency matrix (graph)


printf("Enter the adjacency matrix (0 for no edge, otherwise enter edge
weight):\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}

// Call Floyd-Warshall algorithm to find the shortest paths


floydWarshall(graph, n);

return 0;
}
Output:-
Enter the number of vertices: 4
Enter the adjacency matrix (0 for no edge, otherwise enter edge weight):
0300
3020
0205
0050

Shortest distances between every pair of vertices:


0 3 5 10
3 0 2 7
5 2 0 5
10 7 5 0
Experiment – 10
Aim :- Implement N Queen's problem using Back Tracking.
Program:-
#include <stdio.h>
#include <stdbool.h>

#define MAX 10

// Function to print the chessboard configuration


void printSolution(int board[MAX][MAX], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 1)
printf("Q "); // Print Queen
else
printf(". "); // Empty space
}
printf("\n");
}
}

// Function to check if it's safe to place a queen at board[row][col]


bool isSafe(int board[MAX][MAX], int row, int col, int n) {
// Check this column in the current row
for (int i = 0; i < row; i++) {
if (board[i][col] == 1)
return false;
}

// Check upper-left diagonal


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

// Check upper-right diagonal


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

return true;
}

// Backtracking function to solve the N-Queens problem


bool solveNQueens(int board[MAX][MAX], int row, int n) {
// If all queens are placed
if (row == n)
return true;

// Consider this row and try placing the queen in all columns
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col, n)) {
board[row][col] = 1; // Place the queen

// Recur to place the rest of the queens


if (solveNQueens(board, row + 1, n))
return true;

// If placing queen in board[row][col] doesn't lead to a solution,


backtrack
board[row][col] = 0; // Remove the queen
}
}

return false; // If the queen cannot be placed in any column in this row
}

// Driver function to solve N Queens problem


void nQueens(int n) {
int board[MAX][MAX] = {0}; // Initialize the chessboard with 0s (no queens
placed)

if (solveNQueens(board, 0, n)) {
printSolution(board, n); // Print the solution
} else {
printf("Solution does not exist\n");
}
}

int main() {
int n;

printf("Enter the number of queens: ");


scanf("%d", &n);

nQueens(n); // Solve the N-Queens problem

return 0;
}

Output:-
Enter the number of queens: 8
Q.......
....Q...
.......Q
.....Q..
..Q.....
......Q.
.Q......
...Q....

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy