Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views4 pages

Exp 5dijstra

Uploaded by

studyfocus99.99
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)
5 views4 pages

Exp 5dijstra

Uploaded by

studyfocus99.99
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/ 4

EXPERIMENT NO.

TITLE : Implementation and analysis of Dijstra's algorithm using


greedy method

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

#define V 6 // Number of vertices in the graph

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


int min = INT_MAX, min_index;

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


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

void printSolution(int dist[]) {


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

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


int dist[V]; // Output array: dist[i] will hold shortest distance
from src to i
bool visited[V]; // visited[i] will be true if vertex i is included in
shortest path tree

// Initialize distances to infinity and visited[] to false


for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
visited[i] = false;
}

dist[src] = 0; // Distance to source is always 0

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, visited);
visited[u] = true;

// Update dist[v] only if:


// 1. Not visited
// 2. Edge exists from u to v
// 3. Total weight of path from src to v through u is smaller than
current dist[v]
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];
}
}
}

printSolution(dist);
}

int main() {
// Example graph represented as adjacency matrix
int graph[V][V] = {
{0, 4, 0, 0, 0, 0},
{4, 0, 8, 0, 0, 0},
{0, 8, 0, 7, 0, 4},
{0, 0, 7, 0, 9, 14},
{0, 0, 0, 9, 0, 10},
{0, 0, 4, 14, 10, 0}
};
int source = 0;
dijkstra(graph, source);

return 0;
}
IBRAHIM ABDUL MAJEED PARKAR ROLL NO:43

OUTPUT :

You might also like