DSA Tutorial



DIJKSTRA'S ALGORITHM


🧠 Dijkstra’s Algorithm in DSA (Using C)

Dijkstra’s Algorithm is used to find the shortest paths from a single source node to all other nodes in a weighted graph (with non-negative weights).

πŸ“Œ Key Points:

  • Works with non-negative edge weights
  • Uses greedy strategy to pick the shortest path
  • Efficient with priority queue / min heap
πŸš€ We'll implement a simple matrix-based version of Dijkstra's Algorithm in C.

πŸ’» Dijkstra's Algorithm – C Code

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

#define V 5  // Number of vertices

int minDistance(int dist[], int 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 dijkstra(int graph[V][V], int src) {
    int dist[V];     // Distance from source
    int visited[V];  // Visited vertices

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

    dist[src] = 0;

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

        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\n");
    for (int i = 0; i < V; i++)
        printf("%d \t\t %d\n", i, dist[i]);
}

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

    dijkstra(graph, 0);
    return 0;
}
  

πŸ“€ Output Example

Vertex  Distance from Source
0        0
1        7
2        13
3        8
4        5
  
βœ… Time Complexity: O(VΒ²) using matrix
βœ… Use Min Heap / Priority Queue for better efficiency: O((V + E) log V)

πŸ” Real Life Applications

  • Google Maps (finding shortest routes)
  • Routing protocols in computer networks
  • Game AI navigation

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review