Assignment 4 Solution
Assignment 4 Solution
1. Write a C program to implement single source shortest path (Dijkstra) algorithm for
the following graph with 6 vertices using dynamic programming.
Solution:
#include <stdio.h>
#define INFINITY 9999
#define MAX 10
int main() {
int Graph[MAX][MAX], n, u;
n = 6;
u = 0;
dijkstra(Graph, n, u);
return 0;
}
void dijkstra(int Graph[MAX][MAX], int n, int start) {
int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX], count, mindistance, nextnode, i, j;
distance[start] = 0;
visited[start] = 1;
count = 1;
// Dijkstra's algorithm
while (count < n - 1) {
mindistance = INFINITY;
visited[nextnode] = 1;
count++;
}
int main() {
float temp, temp1, s;
float x[20];
int n, i, j, k;
struct knap {
int profit;
int size;
};
// Swap sizes
temp1 = a[j].size;
a[j].size = a[j + 1].size;
a[j + 1].size = temp1;
}
}
}
float U = s;
float P = 0.0;
3. Write a C Program to find minimum cost spanning tree using Prim’s Algorithm for the
following graph.
#include <stdio.h>
int u, v, n, i, j, ne = 1;
int visited[10] = {0}, min, mincost = 0, cost[10][10];
int main() {
printf("\nEnter the number of nodes: ");
scanf("%d", &n);
printf("\nEnter the 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; // Representing no edge
}
}
visited[1] = 1;
printf("\n");
if (!visited[v]) {
printf("\nEdge %d: (%d %d) cost: %d", ne++, u, v, min);
mincost += min;
visited[v] = 1;
}
return 0;
}