#27.Journey to DSA in C++

#27.Journey to DSA in C++

ยท

4 min read

๐ŸŒŸ Exploring Graph Algorithms: Prim's and Dijkstra's in C++ ๐ŸŒŸ

Hello, dear readers! ๐Ÿ‘‹

I hope you're all doing well today. I'm excited to kick off a new series where I'll be diving into some fascinating topics in computer science and programming. In this series, we'll unravel the mysteries of various algorithms and write some cool code in C++. So, let's get started!

๐ŸŒŸ Understanding Prim's Algorithm ๐ŸŒŸ

In today's session, we're going to explore Prim's Algorithm, a fundamental algorithm used in graph theory. This algorithm helps us find the Minimum Spanning Tree (MST) of a connected, undirected graph. MST is a tree that spans all the vertices of the graph with the minimum possible total edge weight. In simpler terms, it helps us find the most efficient way to connect all points while minimizing the cost.

Prim's Algorithm works by starting with a single vertex and incrementally adding the closest vertices to the existing MST. It's a greedy algorithm that ensures the edges in the tree are always the smallest available. This results in a tree with the least possible weight.

Let's move on to the code! ๐Ÿค–

// Prim's Algorithm in C++

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const int INF = 1e9;

int primMST(vector<vector<pair<int, int>>>& graph, int start) {
    int n = graph.size();
    vector<int> key(n, INF);
    vector<bool> inMST(n, false);

    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

    key[start] = 0;
    pq.push({0, start});

    int minCost = 0;

    while (!pq.empty()) {
        int u = pq.top().second;
        pq.pop();

        if (inMST[u]) continue;

        inMST[u] = true;
        minCost += key[u];

        for (auto& neighbor : graph[u]) {
            int v = neighbor.first;
            int weight = neighbor.second;
            if (!inMST[v] && weight < key[v]) {
                key[v] = weight;
                pq.push({key[v], v});
            }
        }
    }

    return minCost;
}

๐ŸŒ  Introduction to Dijkstra's Shortest Path Algorithm ๐ŸŒ 

Moving on to another exciting topic, Dijkstra's Shortest Path Algorithm! This algorithm helps us find the shortest path from a single source to all other vertices in a weighted graph. Whether you're looking to navigate the most efficient route on a map or optimize network routing, Dijkstra's algorithm is your friend.

It works by maintaining a set of vertices whose minimum distance from the source is known. We keep updating these distances until we've considered all vertices.

Now, let's dive into the code for Dijkstra's Algorithm! ๐Ÿš€

// Dijkstra's Shortest Path Algorithm in C++

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const int INF = 1e9;

vector<int> dijkstra(vector<vector<pair<int, int>>>& graph, int start) {
    int n = graph.size();
    vector<int> dist(n, INF);
    dist[start] = 0;

    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, start});

    while (!pq.empty()) {
        int u = pq.top().second;
        int d = pq.top().first;
        pq.pop();

        if (d > dist[u]) continue;

        for (auto& neighbor : graph[u]) {
            int v = neighbor.first;
            int weight = neighbor.second;

            if (dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }

    return dist;
}

๐Ÿ” Delving Deeper into Prim's Algorithm ๐ŸŒฒ

Now, let's understand the workflow of Prim's Algorithm step by step:

  1. We initialize two arrays, key and inMST. The key array stores the minimum weight to reach each vertex, and inMST keeps track of whether a vertex is included in the MST.

  2. We create a priority queue pq to choose the next vertex with the smallest key value. We start with the first vertex, so its key is set to 0 and pushed into pq.

  3. While pq is not empty, we:

    • Extract the vertex with the smallest key from pq.

    • If the vertex is already in the MST, we skip it.

    • Otherwise, we add it to the MST and update minCost.

    • For all neighboring vertices, if they are not in the MST and have a smaller weight than their current key, we update their key value and push them into pq.

  4. Finally, we return the minCost, which is the weight of the Minimum Spanning Tree.

๐Ÿ” Delving Deeper into Dijkstra's Algorithm ๐Ÿ›ค๏ธ

Now, let's explore the inner workings of Dijkstra's Algorithm:

  1. We initialize an array dist to store the minimum distance from the source vertex to all other vertices. Initially, all distances are set to infinity, except the source itself, which is set to 0.

  2. We create a priority queue pq to pick the vertex with the smallest distance. We start with the source vertex and its distance, and push it into pq.

  3. While pq is not empty, we:

    • Extract the vertex with the smallest distance from pq.

    • If its distance is greater than the stored distance, we skip it.

    • For all neighboring vertices, we calculate the distance from the source to those neighbors through the current vertex. If it's smaller than the current stored distance for the neighbor, we update it and push it into pq.

  4. Finally, we return the dist array, which contains the shortest distances from the source to all other vertices.

That's it for today's session! We've covered Prim's Algorithm and Dijkstra's Shortest Path Algorithm with simple C++ code and explained the inner workings of these essential graph algorithms. I encourage you to try these algorithms out, experiment with different graphs, and see how they work.

Stay tuned for more exciting sessions where we'll explore advanced topics and build upon the knowledge we've gained today. Happy coding! ๐Ÿค“๐Ÿš€

ย