Dijkstra 0001
Dijkstra 0001
Algorithm:
➢ Initialize the cost matrix:
• Create a cost matrix that stores the actual cost (weight) of each edge between nodes. If
➢ Initialization:
• Initialize the distance[] array to store the minimum distance from the start node to each
node. Initially, set this to the direct cost from the start node.
• Initialize the pred[] (predecessor) array to store the previous node in the shortest path.
• Initialize the visited[] array to mark which nodes have been visited. Initially, set all nodes as
unvisited.
• Set the distance from the start node to itself to 0 and mark the start node as visited.
➢ Main Loop:
• Repeat the following steps until all nodes are visited (i.e., count < n - 1):
o Find the next unvisited node with the smallest distance from the start node (referred
to as nextnode).
o Update the distances of the unvisited neighboring nodes of nextnode. For each
➢ Output:
• After visiting all nodes, print the shortest distance from the start node to each other node,
except itself.
#define MAX 10
if (Graph[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = Graph[i][j];
distance[i] = cost[start][i];
pred[i] = start;
visited[i] = 0;
distance[start] = 0;
visited[start] = 1;
count = 1;
mindistance = INFINITY;
mindistance = distance[i];
nextnode = i;
visited[nextnode] = 1;
if (!visited[i])
pred[i] = nextnode;
count++;
if (i != start) {
int main() {
int Graph[MAX][MAX], i, j, n, u;
n = 7;
Graph[0][0] = 0;
Graph[0][1] = 0;
Graph[0][2] = 1;
Graph[0][3] = 2;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;
Graph[1][0] = 0;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][5] = 3;
Graph[1][6] = 0;
Graph[2][0] = 1;
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 1;
Graph[2][4] = 3;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 2;
Graph[3][1] = 0;
Graph[3][2] = 1;
Graph[3][3] = 0;
Graph[3][4] = 0;
Graph[3][5] = 0;
Graph[3][6] = 1;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 3;
Graph[4][3] = 0;
Graph[4][4] = 0;
Graph[4][5] = 2;
Graph[4][6] = 0;
Graph[5][0] = 0;
Graph[5][1] = 3;
Graph[5][3] = 0;
Graph[5][4] = 2;
Graph[5][5] = 0;
Graph[5][6] = 1;
Graph[6][0] = 0;
Graph[6][1] = 0;
Graph[6][2] = 0;
Graph[6][3] = 1;
Graph[6][4] = 0;
Graph[6][5] = 1;
Graph[6][6] = 0;
u = 0;
Dijkstra(Graph, n, u);
return 0;
OUTPUT:
Distance from source to 1: 5