c shortest path dijkstra

To find the shortest path in a graph using Dijkstra's algorithm in C++, you can follow these steps:

  1. Define the necessary data structures:
  2. Create a struct or class to represent a node in the graph. Each node should have an identifier, a list of neighboring nodes, and the weight of the edge connecting them.
  3. Create a priority queue to store the nodes that will be visited during the algorithm. The priority queue should prioritize nodes based on their tentative distance from the source node.

  4. Initialize the graph:

  5. Create an array or vector to store all the nodes in the graph.
  6. Set the distance of the source node to 0 and the distance of all other nodes to infinity.
  7. Add the source node to the priority queue.

  8. Implement the Dijkstra's algorithm:

  9. While the priority queue is not empty:

    • Extract the node with the minimum tentative distance from the priority queue.
    • For each neighboring node of the extracted node:
    • Calculate the tentative distance from the source node to the neighboring node by adding the weight of the edge between them to the tentative distance of the extracted node.
    • If the tentative distance is less than the current distance of the neighboring node:
      • Update the distance of the neighboring node with the tentative distance.
      • Update the previous node of the neighboring node to be the extracted node.
      • Add the neighboring node to the priority queue.
  10. Retrieve the shortest path:

  11. Start from the destination node and follow the previous nodes until you reach the source node. This will give you the shortest path.

Here's a code example that demonstrates the implementation of Dijkstra's algorithm in C++:

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

struct Node {
    int id;
    std::vector<std::pair<Node*, int>> neighbors; // pair of neighboring node and edge weight
    int distance;
    Node* previous;
};

struct CompareNodes {
    bool operator()(const Node n1, const Node n2) {
        return n1->distance > n2->distance;
    }
};

void dijkstra(std::vector<Node>& graph, Node source, Node* destination) {
    std::priority_queue<Node, std::vector<Node>, CompareNodes> pq;

    for (Node* node : graph) {
        node->distance = (node == source ? 0 : INT_MAX);
        node->previous = nullptr;
        pq.push(node);
    }

    while (!pq.empty()) {
        Node* current = pq.top();
        pq.pop();

        if (current == destination) {
            break;
        }

        for (auto& neighbor : current->neighbors) {
            int altDistance = current->distance + neighbor.second;
            if (altDistance < neighbor.first->distance) {
                neighbor.first->distance = altDistance;
                neighbor.first->previous = current;
            }
        }
    }
}

std::vector<Node> getShortestPath(Node source, Node* destination) {
    std::vector<Node*> path;
    Node* current = destination;

    while (current != nullptr) {
        path.insert(path.begin(), current);
        current = current->previous;
    }

    return path;
}

int main() {
    // Create the graph
    Node* nodeA = new Node{1};
    Node* nodeB = new Node{2};
    Node* nodeC = new Node{3};
    Node* nodeD = new Node{4};
    Node* nodeE = new Node{5};

    nodeA->neighbors = {{nodeB, 4}, {nodeC, 2}};
    nodeB->neighbors = {{nodeD, 5}};
    nodeC->neighbors = {{nodeB, 1}, {nodeD, 8}, {nodeE, 10}};
    nodeD->neighbors = {{nodeE, 2}};
    nodeE->neighbors = {};

    std::vector<Node*> graph = {nodeA, nodeB, nodeC, nodeD, nodeE};

    // Run Dijkstra's algorithm
    dijkstra(graph, nodeA, nodeE);

    // Retrieve the shortest path
    std::vector<Node*> shortestPath = getShortestPath(nodeA, nodeE);

    // Print the shortest path
    for (Node* node : shortestPath) {
        std::cout << node->id << " ";
    }
    std::cout << std::endl;

    return 0;
}

Note: This code example assumes a directed graph and uses an adjacency list representation. The Node struct represents a node in the graph, and each node has a list of neighboring nodes with their corresponding edge weights. The dijkstra function implements the Dijkstra's algorithm, and the getShortestPath function retrieves the shortest path from the source to the destination node. The main function demonstrates the usage of these functions with a sample graph.