0% found this document useful (0 votes)
34 views23 pages

DAA Assignment 2 PDF

The document contains multiple programming assignments related to algorithms, including implementations of binary search, merge sort, and greedy algorithms. Each section provides code examples in C for specific problems such as searching in arrays, counting inversions, and solving the fractional knapsack problem. Additionally, it covers concepts like bitonic sequences, finding median neighbors, and optimal matrix multiplication parenthesization.

Uploaded by

kumawatharsh191
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)
34 views23 pages

DAA Assignment 2 PDF

The document contains multiple programming assignments related to algorithms, including implementations of binary search, merge sort, and greedy algorithms. Each section provides code examples in C for specific problems such as searching in arrays, counting inversions, and solving the fractional knapsack problem. Additionally, it covers concepts like bitonic sequences, finding median neighbors, and optimal matrix multiplication parenthesization.

Uploaded by

kumawatharsh191
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/ 23

Assignment 2

NAME - HARSH KUMAWAT


SUBJECT - DAA
ENR.NO - 12023002001129
B TECH 2ND YEAR SECTION - C

1. Implement Binary Search using Divide and Conquer.

Code
#include <stdio.h>

int binarySearch(int arr[], int low, int high, int target) {


if (low <= high) {
int mid = low + (high - low) / 2;

// Check if the target is present at mid


if (arr[mid] == target) {
return mid;
}

// If the target is smaller than mid, search the left subarray


if (target < arr[mid]) {
return binarySearch(arr, low, mid - 1, target);
}

// Otherwise, search the right subarray


return binarySearch(arr, mid + 1, high, target);
}

// Target is not present in the array


return -1;
}

int main() {
int n, target;

// Input the array size


printf("Enter the number of elements in the sorted array: ");
scanf("%d", &n);

int arr[n];
printf("Enter the elements in sorted order:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input the target element


printf("Enter the target element to search: ");
scanf("%d", &target);

int result = binarySearch(arr, 0, n - 1, target);

if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found\n");
}

return 0;
}

2. Apply Binary Search on 2D NxM array (A) having numbers stored in non-
decreasing order under row-major scanning.

Code

#include <stdio.h>

int binarySearch2D(int rows, int cols, int matrix[rows][cols], int target) {


int low = 0;
int high = rows * cols - 1;

while (low <= high) {


int mid = low + (high - low) / 2;
int row = mid / cols;
int col = mid % cols;
int midValue = matrix[row][col];

if (midValue == target) {
printf("Element found at position (%d, %d)\n", row, col);
return 1;
}

if (midValue < target) {


low = mid + 1;
} else {
high = mid - 1;
}
}

printf("Element not found in the matrix.\n");


return 0;
}

int main() {
int rows, cols, target;

// Input matrix dimensions


printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);

int matrix[rows][cols];
printf("Enter elements of the matrix in non-decreasing row-major order:\n");

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


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

// Input target element


printf("Enter the target element to search: ");
scanf("%d", &target);

binarySearch2D(rows, cols, matrix, target);

return 0;
}

3. A Bitonic Sequence is a sequence of numbers which is first strictly


increasing then after a point strictly decreasing. A Bitonic Point is a point in the
bitonic sequence before which elements are strictly increasing and after which
elements are strictly decreasing. Find bitonic points in a bitonic sequence.

Code
#include <stdio.h>
// Function to find the bitonic point using binary search
int findBitonicPoint(int arr[], int low, int high) {
if (low <= high) {
int mid = low + (high - low) / 2;

// Check if the current element is the bitonic point


if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) {
return mid;
}

// If the middle element is in the increasing part


if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) {
return findBitonicPoint(arr, mid + 1, high);
}

// If the middle element is in the decreasing part


return findBitonicPoint(arr, low, mid - 1);
}

return -1;
}

int main() {
int n;

// Input the sequence size


printf("Enter the number of elements in the bitonic sequence: ");
scanf("%d", &n);

int arr[n];
printf("Enter the bitonic sequence: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

int bitonicIndex = findBitonicPoint(arr, 1, n - 2); // Start from 1 to n-2 to avoid


out-of-bound

if (bitonicIndex != -1) {
printf("The bitonic point is %d at index %d\n", arr[bitonicIndex],
bitonicIndex);
} else {
printf("No bitonic point found.\n");
}

return 0;
}

4. Apply Merge Sort to count inversion pairs in an array. Two elements a[i] and
a[j] form an inversion pair if a[i] > a[j] and i < j. Example: The sequence 2, 4, 1, 3,
5 has three inversions (2, 1), (4, 1), (4, 3).

Code
#include <stdio.h>

int mergeAndCount(int arr[], int temp[], int left, int mid, int right) {
int i = left; // Left subarray index
int j = mid + 1; // Right subarray index
int k = left; // Merged array index
int invCount = 0;

while (i <= mid && j <= right) {


if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
// Inversion found: all remaining elements in the left subarray
invCount += (mid - i + 1);
temp[k++] = arr[j++];
}
}

// Copy remaining elements from left subarray


while (i <= mid) {
temp[k++] = arr[i++];
}

// Copy remaining elements from right subarray


while (j <= right) {
temp[k++] = arr[j++];
}

// Copy merged elements back to original array


for (i = left; i <= right; i++) {
arr[i] = temp[i];
}

return invCount;
}
int mergeSortAndCount(int arr[], int temp[], int left, int right) {
int invCount = 0;

if (left < right) {


int mid = left + (right - left) / 2;

// Recursively count inversions in left and right subarrays


invCount += mergeSortAndCount(arr, temp, left, mid);
invCount += mergeSortAndCount(arr, temp, mid + 1, right);

// Count cross inversions and merge sorted subarrays


invCount += mergeAndCount(arr, temp, left, mid, right);
}

return invCount;
}

int main() {
int n;

// Input array size


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

int arr[n], temp[n];

// Input array elements


printf("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

int inversionCount = mergeSortAndCount(arr, temp, 0, n - 1);

printf("Number of inversion pairs: %d\n", inversionCount);

return 0;
}

5. Implement a greedy algorithm to solve the fractional knapsack problem.


Code

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

// Structure to represent an item with weight, value, and value/weight ratio


typedef struct {
int weight;
int value;
double ratio;
} Item;

// Comparator function for sorting items by value/weight ratio in descending


order int compare(const void *a, const void *b) { Item *itemA = (Item *)a;
Item *itemB = (Item *)b; if (itemB->ratio > itemA->ratio) return 1; else if
(itemB->ratio < itemA->ratio) return -1;

return 0;
}

double fractionalKnapsack(int W, Item items[], int n) {


// Sort items by value-to-weight ratio
qsort(items, n, sizeof(Item), compare);

double maxValue = 0.0; // Maximum total value


int currentWeight = 0; // Current weight in knapsack

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


if (currentWeight + items[i].weight <= W) {
// Take the entire item
currentWeight += items[i].weight;
maxValue += items[i].value;
} else {
// Take the fraction of the item that fits
int remainingWeight = W - currentWeight;
maxValue += items[i].value * ((double)remainingWeight /
items[i].weight);
break;
}
}

return maxValue;
}
int main() {
int n, W;

// Input number of items and knapsack capacity


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

Item items[n];

printf("Enter the weight and value of each item:\n");


for (int i = 0; i < n; i++) {
printf("Item %d (weight value): ", i + 1);
scanf("%d %d", &items[i].weight, &items[i].value);
items[i].ratio = (double)items[i].value / items[i].weight;
}

printf("Enter the knapsack capacity: ");


scanf("%d", &W);

double maxValue = fractionalKnapsack(W, items, n);

printf("Maximum value in knapsack = %.2lf\n", maxValue);

return 0;
}

6. Find the second largest and second smallest number simultaneously in an


array using Divide & Conquer Principle.

Code

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

// Structure to store the result


typedef struct {
int largest;
int secondLargest;
int smallest;
int secondSmallest;
} Result;
// Helper function to find the required values using Divide & Conquer
Result findSecondLargestSmallest(int arr[], int low, int high) {
Result result;

// Base Case: Single element


if (low == high) {
result.largest = result.secondLargest = arr[low];
result.smallest = result.secondSmallest = arr[low];
return result;
}

// Base Case: Two elements


if (high == low + 1) {
if (arr[low] > arr[high]) {
result.largest = arr[low];
result.secondLargest = arr[high];
result.smallest = arr[high];
result.secondSmallest = arr[low];
} else {
result.largest = arr[high];
result.secondLargest = arr[low];
result.smallest = arr[low];
result.secondSmallest = arr[high];
}
r e t u r n r e s u l t ;
}

// Divide the array


int mid = (low + high) / 2;

Result leftResult = findSecondLargestSmallest(arr, low, mid);


Result rightResult = findSecondLargestSmallest(arr, mid + 1, high);

// Combine results for the largest and second largest


if (leftResult.largest > rightResult.largest) {
result.largest = leftResult.largest;
result.secondLargest = (leftResult.secondLargest > rightResult.largest) ?
leftResult.secondLargest : rightResult.largest;
} else {
result.largest = rightResult.largest;
result.secondLargest = (rightResult.secondLargest > leftResult.largest) ?
rightResult.secondLargest : leftResult.largest;
}

// Combine results for the smallest and second smallest


if (leftResult.smallest < rightResult.smallest) {
result.smallest = leftResult.smallest;
result.secondSmallest = (leftResult.secondSmallest <
rightResult.smallest) ? leftResult.secondSmallest : rightResult.smallest;
} else {
result.smallest = rightResult.smallest;
result.secondSmallest = (rightResult.secondSmallest <
leftResult.smallest) ? rightResult.secondSmallest : leftResult.smallest;
}

return result;
}

int main() {
int n;

// Input the array size


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

int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

if (n < 2) {
printf("Array must have at least two elements.\n");
return 0;
}

Result result = findSecondLargestSmallest(arr, 0, n - 1);

printf("Second Largest: %d\n", result.secondLargest);


printf("Second Smallest: %d\n", result.secondSmallest);

return 0;
}

7. Find neighbors of the median element in an array using the partitioning


strategy of the Quick-Sorting method.

Code
#include <stdio.h>
// Partition function (Lomuto partition scheme)
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] <= pivot) {
i++; int temp =
arr[i]; arr[i] =
arr[j]; arr[j] =
temp;
}
}

// Swap pivot to its correct position


int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;

return i + 1;
}

// QuickSelect function to find kth smallest element


int quickSelect(int arr[], int low, int high, int k) {
if (low <= high) {
int pivotIndex = partition(arr, low, high);

if (pivotIndex == k) {
return arr[pivotIndex];
} else if (pivotIndex > k) {
return quickSelect(arr, low, pivotIndex - 1, k);
} else {
return quickSelect(arr, pivotIndex + 1, high, k);
}
}
r e t u r n - 1 ;
}

void findMedianNeighbors(int arr[], int n) {


int medianIndex = (n - 1) / 2;

int median = quickSelect(arr, 0, n - 1, medianIndex);

printf("Median element: %d\n", median);

// Print neighbors of the median


if (medianIndex > 0) {
printf("Left Neighbor: %d\n", quickSelect(arr, 0, n - 1, medianIndex - 1));
} else {
printf("Left Neighbor: None\n");
}

if (medianIndex < n - 1) {
printf("Right Neighbor: %d\n", quickSelect(arr, 0, n - 1, medianIndex + 1));
} else {
printf("Right Neighbor: None\n");
}
}

int main() {
int n;

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


scanf("%d", &n);

int arr[n];

printf("Enter the elements of the array: ");


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

findMedianNeighbors(arr, n);

return 0;
}

8. Given an array p[ ] which represents the chain of matrices such that the i-th
matrix Ai is of dimension p[i-1] x p[i]. We need to write a function that should
return the optimal parenthesizing expression resulting in a minimum
multiplication cost to multiply the chain.

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

// Function to print optimal parenthesization


void printParenthesis(int i, int j, int n, int bracket[n][n], char *name) {
if (i == j) {
printf("%c", (*name)++);
return;
}
p r i n t f ( " ( " ) ;
printParenthesis(i, bracket[i][j], n, bracket, name);
printParenthesis(bracket[i][j] + 1, j, n, bracket, name);
printf(")");
}

void matrixChainOrder(int p[], int n) {


int m[n][n];
int bracket[n][n]; // Stores optimal parenthesization indices

// Initialize the cost of multiplying one matrix to zero


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

// L is chain length
for (int L = 2; L < n; L++) {
for (int i = 1; i < n - L + 1; i++) {
int j = i + L - 1;
m[i][j] = INT_MAX;

for (int k = i; k < j; k++) {


int cost = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];

if (cost < m[i][j]) {


m[i][j] = cost;
bracket[i][j] = k;
}
}
}
}

printf("Minimum number of multiplications: %d\n", m[1][n - 1]);


char name = 'A';
printf("Optimal Parenthesization: ");
printParenthesis(1, n - 1, n, bracket, &name);
printf("\n");
}

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

int p[n + 1];


printf("Enter the dimensions array (length %d): ", n + 1);
for (int i = 0; i <= n; i++) {
scanf("%d", &p[i]);
}

matrixChainOrder(p, n + 1);

return 0;
}

9. Given weights and values of n items, put these items in a knapsack of


capacity W to get the maximum total value in the knapsack. You cannot break
an item, either pick the item, or don’t pick it.

Code
#include <stdio.h>

// Function to solve 0/1 Knapsack using DP


int knapsack(int W, int weights[], int values[], int n) {
int dp[n + 1][W + 1];

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


for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0) {
dp[i][w] = 0;
} else if (weights[i - 1] <= w) {
dp[i][w] = (values[i - 1] + dp[i - 1][w - weights[i - 1]] > dp[i - 1][w])
? values[i - 1] + dp[i - 1][w - weights[i - 1]]
: dp[i - 1][w];
} else {
dp[i][w] = dp[i - 1][w];
}
}
}

return dp[n][W];
}
int main() {
int n, W;

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


scanf("%d", &n);

int weights[n], values[n];


printf("Enter weights and values of each item:\n");
for (int i = 0; i < n; i++) {
printf("Item %d (weight value): ", i + 1);
scanf("%d %d", &weights[i], &values[i]);
}

printf("Enter the knapsack capacity: ");


scanf("%d", &W);

int maxValue = knapsack(W, weights, values, n);

printf("Maximum total value in knapsack = %d\n", maxValue);

return 0;
}

10. Implement the greedy algorithm to solve the problem of the Job Sequencing
with deadlines.

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

// Structure to represent a job


typedef struct {
int id; // Job ID
int deadline; // Deadline
int profit; // Profit
} Job;

// Comparison function to sort jobs by profit in descending order


int compareJobs(const void *a, const void *b) {
return ((Job *)b)->profit - ((Job *)a)->profit;
}
// Function to perform Job Sequencing void jobSequencing(Job
jobs[], int n) { qsort(jobs, n, sizeof(Job), compareJobs); // Sort jobs
by profit

bool slot[n]; // Track free time slots


int jobSequence[n]; // Store result sequence of jobs

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


slot[i] = false;
}

int maxProfit = 0;
int jobCount = 0;

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


for (int j = (jobs[i].deadline - 1 < n ? jobs[i].deadline - 1 : n - 1); j >= 0; j--) {
if (!slot[j]) { // If slot is free
slot[j] = true;
jobSequence[j] = jobs[i].id;
maxProfit += jobs[i].profit;
jobCount++;
break;
}
}
}

printf("Job Sequence: ");


for (int i = 0; i < n; i++) {
if (slot[i]) {
printf("Job%d ", jobSequence[i]);
}
}
printf("\nTotal Profit: %d\n", maxProfit);
}

int main() {
int n;

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


scanf("%d", &n);

Job jobs[n];

printf("Enter job details (ID, Deadline, Profit):\n");


for (int i = 0; i < n; i++) {
printf("Job %d: ", i + 1);
scanf("%d %d %d", &jobs[i].id, &jobs[i].deadline, &jobs[i].profit);
}

jobSequencing(jobs, n);

return 0;
}

11. Implement a greedy algorithm for finding the single-source shortest paths.
Suggest an algorithm if the given graph contains negative weights and non-
negative weight cycle and implement it.

Dijkstra Algorithm for Non-Negative Weights


Code

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

#define V 5 // Number of vertices

int minDistance(int dist[], bool visited[]) {


int min = INT_MAX, minIndex;

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


if (!visited[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}

void dijkstra(int graph[V][V], int src) {


int dist[V];
bool visited[V];

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


dist[i] = INT_MAX;
visited[i] = false;
}
dist[src] = 0;

for (int count = 0; count < V - 1; count++) {


int u = minDistance(dist, visited);
visited[u] = true;

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


if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] +
graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

printf("Vertex\tDistance from Source %d\n", src);


for (int i = 0; i < V; i++) {
printf("%d\t%d\n", i, dist[i]);
}
}

int main() {
int graph[V][V] = {
{0, 10, 0, 0, 5},
{0, 0, 1, 0, 2},
{0, 0, 0, 4, 0},
{7, 0, 6, 0, 0},
{0, 3, 9, 2, 0}
};

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

dijkstra(graph, src);

return 0;
}

12. Apply Strassen’s Matrix Multiplication strategy for odd dimensional square
matrices.
Code
#include <stdio.h>
#include <stdlib.h>

#define MAX 3 // Assuming the square matrix dimension is odd and MAX x MAX

// Helper function to add two matrices


void addMatrix(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX]) {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}

// Helper function to subtract two matrices


void subtractMatrix(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX]) {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
C[i][j] = A[i][j] - B[i][j];
}
}
}

// Function for Strassen's Matrix Multiplication


void strassenMultiply(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX]) {
int M1, M2, M3, M4, M5, M6, M7;

// Calculate products using Strassen's formula


M1 = (A[0][0] + A[1][1]) * (B[0][0] + B[1][1]);
M2 = (A[1][0] + A[1][1]) * B[0][0];
M3 = A[0][0] * (B[0][1] - B[1][1]);
M4 = A[1][1] * (B[1][0] - B[0][0]);
M5 = (A[0][0] + A[0][1]) * B[1][1];
M6 = (A[1][0] - A[0][0]) * (B[0][0] + B[0][1]);
M7 = (A[0][1] - A[1][1]) * (B[1][0] + B[1][1]);

C[0][0] = M1 + M4 - M5 + M7;
C[0][1] = M3 + M5; C[1][0] = M2
+ M4; C[1][1] = M1 - M2 + M3 +
M6; }

// Driver code
int main() {
int A[MAX][MAX] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int B[MAX][MAX] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int C[MAX][MAX] = {0};

strassenMultiply(A, B, C);

printf("Resultant Matrix:\n");
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
printf("%d ", C[i][j]);
}
p r i n t f ( " \ n " ) ;
}

return 0;
}

13. Given a cost 2D-matrix and a position (m, n), write a function that returns
the minimum cost-path to reach (m, n) from (0, 0).

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

#define N 3

int min(int x, int y, int z) {


int minVal = (x < y) ? x : y;
return (minVal < z) ? minVal : z;
}

int minCostPath(int cost[N][N], int m, int n) {


int dp[N][N];
dp[0][0] = cost[0][0];

// Initialize first row


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

// Initialize first column


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

// Fill the rest of the dp matrix


for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = cost[i][j] + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
}
}

return dp[m][n];
}

int main() {
int cost[N][N] = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}};
int m = 2, n = 2;

printf("Minimum cost to reach (%d, %d) is %d\n", m, n, minCostPath(cost, m,


n));

return 0;
}

14. Given a value V and an infinite supply of coins of m-denominations


{C1=1<C2<C3<.. <Cm}, we want to make change for Rs. V. Apply DP strategy to
find out the minimum number of coins to make the change
Code
#include <stdio.h>
#include <limits.h>

int coinChange(int coins[], int m, int V) {


int dp[V + 1];
dp[0] = 0;

for (int i = 1; i <= V; i++) {


dp[i] = INT_MAX;
for (int j = 0; j < m; j++) {
if (coins[j] <= i && dp[i - coins[j]] != INT_MAX) {
dp[i] = (dp[i] < dp[i - coins[j]] + 1) ? dp[i] : dp[i - coins[j]] + 1;
}
}
}
return dp[V] == INT_MAX ? -1 : dp[V];
}

int main() {
int coins[] = {1, 2, 5};
int m = sizeof(coins) / sizeof(coins[0]);
int V;

printf("Enter the value to make change for: ");


scanf("%d", &V);

int result = coinChange(coins, m, V);


if (result != -1) {
printf("Minimum coins required: %d\n", result);
} else {
printf("Change cannot be made for %d\n", V);
}

return 0;
}

15. Implement all pairs of the shortest path algorithms for a graph using Floyd
Warshall’s strategy.

Code

#include <stdio.h>
#define INF 99999
#define V 4

void floydWarshall(int graph[V][V]) {


int dist[V][V];

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


for (int j = 0; j < V; j++) {
dist[i][j] = graph[i][j];
}
}

for (int k = 0; k < V; k++) {


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

printf("Shortest distances between every pair of vertices:\n");


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF) {
printf("%7s", "INF");
} else {
printf("%7d", dist[i][j]);
}
}
p r i n t f ( " \ n " ) ;
}
}

int main() {
int graph[V][V] = {
{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}
};

floydWarshall(graph);

return 0;
}

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