Shortest Path Algorithms (Dijkstra, Bellman-Ford)

๐Ÿ“˜ Data Structure and Algorithm ๐Ÿ‘ 132 views ๐Ÿ“… Nov 05, 2025
โฑ Estimated reading time: 2 min

Shortest Path Algorithms (Dijkstra and Bellman-Ford)

The shortest path problem finds the path between two vertices that minimizes the total edge weight. Two popular algorithms for this are Dijkstraโ€™s Algorithm and Bellman-Ford Algorithm.

1. Dijkstraโ€™s Algorithm

Dijkstraโ€™s algorithm finds the shortest path from a source vertex to all other vertices in a weighted graph with non-negative edges.

// Example: Dijkstraโ€™s Algorithm (C++)
void dijkstra(int V, vector>>& adj, int src) {
    vector dist(V, INT_MAX);
    priority_queue, vector>, greater>> pq;
    dist[src] = 0;
    pq.push({0, src});

    while (!pq.empty()) {
        int u = pq.top().second;
        pq.pop();
        for (auto it : adj[u]) {
            int v = it.first;
            int weight = it.second;
            if (dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }
}

Time Complexity:

O((V + E) log V) using a priority queue.

2. Bellman-Ford Algorithm

Bellman-Ford can handle graphs with negative edge weights. It relaxes all edges (Vโˆ’1) times to find the shortest path.

// Example: Bellman-Ford Algorithm (C++)
void bellmanFord(int V, vector>& edges, int src) {
    vector dist(V, INT_MAX);
    dist[src] = 0;
    for (int i = 0; i < V - 1; i++) {
        for (auto e : edges) {
            int u = e[0], v = e[1], w = e[2];
            if (dist[u] != INT_MAX && dist[u] + w < dist[v])
                dist[v] = dist[u] + w;
        }
    }
}

Time Complexity:

O(V * E)

Comparison

AlgorithmHandles Negative WeightsTime Complexity
DijkstraNoO((V + E) log V)
Bellman-FordYesO(V * E)

Applications

  • GPS and navigation systems
  • Network routing protocols
  • Optimal path finding in weighted graphs

Conclusion

Both Dijkstra and Bellman-Ford algorithms are essential for solving shortest path problems. Dijkstraโ€™s is faster for non-negative graphs, while Bellman-Ford is versatile and can detect negative cycles.


๐Ÿ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


โ† Back to Tutorials

Popular Competitive Exam Quizzes

๐Ÿค– AI Quizer Assistant

๐Ÿ“ Quiz
๐Ÿ“š Categories
๐Ÿ† Leaderboard
๐Ÿ“Š My Score
โ“ Help
๐Ÿ‘‹ Hi! I'm your AI quiz assistant for Quizer.in!

I can help you with:
โ€ข ๐Ÿ“ Finding quizzes
โ€ข ๐Ÿ† Checking leaderboard
โ€ข ๐Ÿ“Š Your performance stats

Type 'help' to get started! ๐Ÿš€
AI is thinking...