-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesign Graph With Shortest Path Calculator.cpp
88 lines (67 loc) Β· 2.59 KB
/
Design Graph With Shortest Path Calculator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*class Graph {
public:
Graph(int n, vector<vector<int>>& edges) {
}
void addEdge(vector<int> edge) {
}
int shortestPath(int node1, int node2) {
}
};
/**
* Your Graph object will be instantiated and called as such:
* Graph* obj = new Graph(n, edges);
* obj->addEdge(edge);
* int param_2 = obj->shortestPath(node1,node2);
*/
class Graph {
public:
// Adjacency list to represent the graph
vector<vector<pair<int, int>>> adjacencyList;
// Constructor to initialize the graph with nodes and edges
Graph(int n, vector<std::vector<int>>& edges) {
adjacencyList.resize(n);
for (auto edge : edges)
adjacencyList[edge[0]].emplace_back(edge[1], edge[2]);
}
// Add a new edge to the graph
void addEdge(vector<int> edge) {
adjacencyList[edge[0]].emplace_back(edge[1], edge[2]);
}
// Find the shortest path between two nodes using Dijkstra's algorithm
int shortestPath(int node1, int node2) {
return dijkstra(node1, node2);
}
private:
// Dijkstra's algorithm to find the shortest path
int dijkstra(int start, int end) {
int n = adjacencyList.size();
vector<int> distances(n, INT_MAX);
distances[start] = 0;
// Priority queue to efficiently retrieve the node with the minimum distance
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> priorityQueue;
priorityQueue.push({0, start});
while (!priorityQueue.empty()) {
int currentNode = priorityQueue.top().second;
int currentCost = priorityQueue.top().first;
priorityQueue.pop();
// Skip if a shorter path has already been found
if (currentCost > distances[currentNode])
continue;
// If found the target node then return the cost
if(currentNode == end)
return currentCost ;
// Explore neighbors and update distances
for (auto edge : adjacencyList[currentNode]) {
int neighbor = edge.first, edgeLength = edge.second;
int newRouteCost = edgeLength + distances[currentNode];
// Update distance if a shorter route is found
if (distances[neighbor] > newRouteCost) {
distances[neighbor] = newRouteCost;
priorityQueue.push({newRouteCost, neighbor});
}
}
}
// Return the minimum distance or -1 if no path exists
return ((distances[end] == INT_MAX) ? -1 : distances[end]);
}
};