Sponsored
Sponsored
The Floyd-Warshall algorithm is a classical dynamic programming algorithm to solve the all-pairs shortest path problem. It works well for graphs that have both weighted and unweighted edges. The algorithm iteratively updates the distance matrix for each possible intermediate node and provides the shortest distances between any two nodes.
The algorithm has a time complexity of O(n^3)
and a space complexity of O(n^2)
, making it suitable for graphs with up to 100 nodes as given in the problem constraints.
Time Complexity: O(n^3)
, where n
is the number of cities.
Space Complexity: O(n^2)
for storing the distance matrix.
1#include <iostream>
2#include <vector>
3#include <climits>
4
5int findTheCity(int n, std::vector<std::vector<int>>& edges, int distanceThreshold) {
6 std::vector<std::vector<int>> dist(n, std::vector<int>(n, INT_MAX));
7
8 for (int i = 0; i < n; ++i) dist[i][i] = 0;
9
10 for (auto& edge : edges) {
11 int u = edge[0], v = edge[1], weight = edge[2];
12 dist[u][v] = weight;
13 dist[v][u] = weight;
14 }
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (dist[i][k] < INT_MAX && dist[k][j] < INT_MAX && dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
int city = -1, minReachableCities = INT_MAX;
for (int i = 0; i < n; ++i) {
int reachableCities = 0;
for (int j = 0; j < n; ++j) {
if (i != j && dist[i][j] <= distanceThreshold) {
++reachableCities;
}
}
if (reachableCities <= minReachableCities) {
minReachableCities = reachableCities;
city = i;
}
}
return city;
}
int main() {
int n = 4;
std::vector<std::vector<int>> edges = {{0, 1, 3}, {1, 2, 1}, {1, 3, 4}, {2, 3, 1}};
int distanceThreshold = 4;
std::cout << findTheCity(n, edges, distanceThreshold) << std::endl;
return 0;
}
This C++ solution uses the Floyd-Warshall algorithm to update the distance matrix, then counts the number of neighbors at each city node. It finally chooses the city with minimal reachable neighbors but with the highest index when ties occur.
Dijkstra's Algorithm can be employed to find the shortest path from one city to another in a graph with non-negative weights. We can utilize this algorithm to determine the shortest distance from every city to all other cities consecutively, assessing the count of reachable cities within the threshold afterward.
Time Complexity: O(n^2)
for each node multiplied by n
trips resulting in O(n^3)
.
Space Complexity: O(n^2)
for graph storage.
This solution leverages Dijkstra's algorithm separately on each city to compute all pairs shortest distance, and subsequently determines the smallest neighbors count within a specific threshold.