DSA Tutorial



SHORTEST PATH IN DSA


๐Ÿงญ Shortest Path in DSA (Using C)

The Shortest Path in a graph refers to finding the minimum distance between two nodes. This is crucial in routing, navigation, and optimization problems.

โœจ Common Shortest Path Algorithms:

  • Dijkstraโ€™s Algorithm (for weighted graphs with non-negative edges)
  • Bellman-Ford Algorithm (handles negative edges)
  • Floyd-Warshall Algorithm (for all-pairs shortest path)
๐Ÿš€ We will implement Dijkstraโ€™s Algorithm using C to find the shortest path from a source node to all other nodes.

๐Ÿ’ป Dijkstra's Algorithm in C

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

#define V 5

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]; // Shortest distance from src to i
    int visited[V]; // True if vertex i is finalized

    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, 2, 0, 6, 0},
        {2, 0, 3, 8, 5},
        {0, 3, 0, 0, 7},
        {6, 8, 0, 0, 9},
        {0, 5, 7, 9, 0}
    };

    dijkstra(graph, 0);
    return 0;
}
  

๐Ÿ“ค Output Example

Vertex  Distance from Source
0        0
1        2
2        5
3        6
4        7
  
โœ… Time Complexity: O(Vยฒ) for matrix-based approach
โœ… Use a priority queue (heap) for O((V+E) log V) efficiency in sparse graphs.

๐Ÿ“š Use Case

Used in GPS systems, routing in networks, and many path-finding problems in games and robotics.


๐ŸŒŸ 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