-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlab12-SSSP.cpp
More file actions
97 lines (77 loc) · 2.67 KB
/
lab12-SSSP.cpp
File metadata and controls
97 lines (77 loc) · 2.67 KB
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
89
90
91
92
93
94
95
96
97
#include <iostream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
// Structure to represent a city and its distance from the source city
struct City {
int id;
int distance;
};
// Comparator for the priority queue
struct CityComparator {
bool operator()(const City& c1, const City& c2) {
return c1.distance > c2.distance;
}
};
// Function to find the shortest time between the source city and all other cities
void findShortestTime(const vector<vector<int>>& graph, int source) {
int numCities = graph.size();
vector<int> distances(numCities, INT_MAX); // Stores the shortest time from the source city
vector<int> parent(numCities, -1); // Stores the parent city of each city in the shortest path
vector<bool> visited(numCities, false); // Tracks visited cities
// Priority queue to store cities and their distances
priority_queue<City, vector<City>, CityComparator> pq;
// Enqueue the source city with a distance of 0
pq.push({source, 0});
distances[source] = 0;
while (!pq.empty()) {
// Dequeue the city with the minimum distance
City currentCity = pq.top();
pq.pop();
int city = currentCity.id;
// Skip if the city is already visited
if (visited[city]) {
continue;
}
visited[city] = true;
// Explore all neighboring cities
for (int neighbor = 0; neighbor < numCities; neighbor++) {
int travelTime = graph[city][neighbor];
// Update distance if a shorter path is found
if (travelTime > 0 && distances[city] + travelTime < distances[neighbor]) {
distances[neighbor] = distances[city] + travelTime;
parent[neighbor] = city;
pq.push({neighbor, distances[neighbor]});
}
}
}
// Print the shortest time and path from the source city to each city
for (int city = 0; city < numCities; city++) {
cout << "From " << source << " to " << city << " : " << distances[city] << endl;
// Print the shortest path
cout << " (Path: ";
int node = city;
while (node != -1) {
cout << node;
node = parent[node];
if (node != -1) {
cout << " -> ";
}
}
cout << ")" << endl;
}
}
int main() {
vector<vector<int>> graph = {
{0, 10, 0, 0, 15, 5},
{10, 0, 10, 30, 0, 0},
{0, 10, 0, 12, 5, 0},
{0, 30, 12, 0, 0, 20},
{15, 0, 5, 0, 0, 0},
{5, 0, 0, 20, 0, 0}
};
int sourceCity = 5;
findShortestTime(graph, sourceCity);
return 0;
}