# Dijkstra Algorithm

## Dijkstra Algorithm

Dijkstra algorithm is a single source shortest path algorithm and  single-source means their only one source is given and find the shortest path from the source to all the nodes.

## Example of Dijkstra’s algorithm

Consider the following figure

## Program of dijkstra’s Algorithm

#include <stdio.h>
#define INFINITY 9999
#define MAX 10

void Dijkstra(int Graph[MAX][MAX], int n, int start);

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;

for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (Graph[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = Graph[i][j];

for (i = 0; i < n; i++) {
distance[i] = cost[start][i];
pred[i] = start;
visited[i] = 0;
}

distance[start] = 0;
visited[start] = 1;
count = 1;

while (count < n - 1) {
mindistance = INFINITY;

for (i = 0; i < n; i++)
if (distance[i] < mindistance && !visited[i]) {
mindistance = distance[i];
nextnode = i;
}

visited[nextnode] = 1;
for (i = 0; i < n; i++)
if (!visited[i])
if (mindistance + cost[nextnode][i] < distance[i]) {
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode;
}
count++;
}

for (i = 0; i < n; i++)
if (i != start) {
printf("\nDistance from source to %d: %d", i, distance[i]);
}
}
int main() {
int Graph[MAX][MAX], i, j, n, u;
n = 7;

Graph = 0;
Graph = 0;
Graph = 1;
Graph = 2;
Graph = 0;
Graph = 0;
Graph = 0;

Graph = 0;
Graph = 0;
Graph = 2;
Graph = 0;
Graph = 0;
Graph = 3;
Graph = 0;

Graph = 1;
Graph = 2;
Graph = 0;
Graph = 1;
Graph = 3;
Graph = 0;
Graph = 0;

Graph = 2;
Graph = 0;
Graph = 1;
Graph = 0;
Graph = 0;
Graph = 0;
Graph = 1;

Graph = 0;
Graph = 0;
Graph = 3;
Graph = 0;
Graph = 0;
Graph = 2;
Graph = 0;

Graph = 0;
Graph = 3;
Graph = 0;
Graph = 0;
Graph = 2;
Graph = 0;
Graph = 1;

Graph = 0;
Graph = 0;
Graph = 0;
Graph = 1;
Graph = 0;
Graph = 1;
Graph = 0;

u = 0;
Dijkstra(Graph, n, u);

return 0;
}

## Output

Distance from source to 1: 3
Distance from source to 2: 1
Distance from source to 3: 2
Distance from source to 4: 4
Distance from source to 5: 4
Distance from source to 6: 3

1. It is its little complexity which is almost linear.

2. Dijkstra algorithm can be used to calculate the shortest path between a single node to all other nodes and a single source node to a single destination node by stop the algorithm once the shortest distance is achieved for the destination node.

3. This algorithm only works for directed graph, weighted graphs and all edges should have non-negative values.

1. This algorithm does an obscured exploration that consumes a lot of time while processing,

2. It is not able to handle negative edges.

3. As it heads to the acyclic graph, so can’t achieve the accurate shortest path and there is a need to maintain tracking of vertices, have been visited

## O(E Log V)

Where, E is the number of edges

V is the number of vertices.

## Space Complexity

O(V)