There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi,weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distance Threshold. Find out a city with the smallest number of cities that are reachable through some path and whose distance is at most Threshold Distance.
If there are multiple such cities, our answer will be the city with the greatest number.
Input : N=4, M=4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation:
The adjacent cities for each city at a distanceThreshold are =
City 0 →[City 1, City 2]
City 1 →[City 0, City 2, City 3]
City 2 →[City 0, City 1, City 3]
City 3 →[City 1, City 2]
Here, City 0 and City 3 have a minimum number of cities
i.e. 2 within distanceThreshold. So, the result will be the
city with the largest number. So, the answer is City 3.
Input : N=3, M=2, edges = [[0,1,1],[0,2,3]], distanceThreshold = 2
Output: 2
Explanation:
City 0 -> City 1,
City 1 → City 0,
City 2 → no City
Hence, 2 is the answer.
Input: N = 3, M = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], distanceThreshold = 2
To find out which city is having the smallest number of cities that are reachable with at most Threshold distance, we firstly need to find the distance betweeen every two pair of nodes(cities) possible then it can be compared with the threshold distance to get the answer.
In order to find the distance between every two pair of nodes, the Floyd Warshall Algorithm can be used. Once the 2D distance matrix(that contains the shortest paths) is generated, for each node(city), we can count the number of nodes(cities) that can be reached with a distance lesser or equal to the Threshold distance.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to find the city with
the smallest number of neighbors. */
int findCity(int n, int m, vector<vector<int>>& edges,
int distanceThreshold) {
// Adjacency matrix to store the graph
vector<vector<int>> adjMat(n, vector<int>(n, 1e9));
// Filling up the adjacency matrix
for(auto it : edges) {
adjMat[it[0]][it[1]] = it[2];
adjMat[it[1]][it[0]] = it[2];
}
// Applying Floyd Warshall Algorithm
// For intermediate node k
for(int k=0; k<n; k++) {
// node i ---> node j
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
adjMat[i][j] =
min(adjMat[i][j], adjMat[i][k] + adjMat[k][j]);
}
}
}
// To store the minimum count of neighbors
int minCount = 1e9;
/* To store the answer (city having
smallest number of neighbors) */
int ans;
// Check every city
for(int i=0; i<n; i++) {
/* To count the neighbors of given city
having distance lesser than threshold */
int count = 0;
// City i ---> City j
for(int j=0; j<n; j++) {
/* If the distance to reach city j from
city i is less than threshold */
if(i != j && adjMat[i][j] <= distanceThreshold) {
// Increment count
count++;
}
}
// if current count is less than minimum count
if(count < minCount) {
// Update minimum count
minCount = count;
// Store the answer
ans = i;
}
/* Else if current count is
equal to minimum count */
else if(count == minCount) {
/* Update the answer (to store
city with greater number) */
ans = i;
}
}
// Return the resulting city as answer
return ans;
}
};
int main() {
int N=4, M=4;
vector<vector<int>> edges ={
{0,1,3},{1,2,1},
{1,3,4},{2,3,1}
};
int distanceThreshold = 4;
/* Creating an instance of
Solution class */
Solution sol;
/* Function to find the city with
the smallest number of neighbors. */
int ans = sol.findCity(N, M, edges, distanceThreshold);
// Output
cout << "The city with smallest number of neighbors (with given threshold) is: " << ans;
return 0;
}
import java.util.*;
class Solution {
/* Function to find the city with
the smallest number of neighbors. */
public int findCity(int n, int m, int[][] edges,
int distanceThreshold) {
// Adjacency matrix to store the graph
int[][] adjMat = new int[n][n];
for (int[] row : adjMat) Arrays.fill(row, (int)1e9);
// Filling up the adjacency matrix
for(int[] it : edges) {
adjMat[it[0]][it[1]] = it[2];
adjMat[it[1]][it[0]] = it[2];
}
// Applying Floyd Warshall Algorithm
// For intermediate node k
for(int k = 0; k < n; k++) {
// node i ---> node j
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
adjMat[i][j] =
Math.min(adjMat[i][j], adjMat[i][k] + adjMat[k][j]);
}
}
}
// To store the minimum count of neighbors
int minCount = (int)1e9;
/* To store the answer (city having
smallest number of neighbors) */
int ans = -1;
// Check every city
for(int i = 0; i < n; i++) {
/* To count the neighbors of given city
having distance lesser than threshold */
int count = 0;
// City i ---> City j
for(int j = 0; j < n; j++) {
/* If the distance to reach city j from
city i is less than threshold */
if(i != j && adjMat[i][j] <= distanceThreshold) {
// Increment count
count++;
}
}
// if current count is less than minimum count
if(count < minCount) {
// Update minimum count
minCount = count;
// Store the answer
ans = i;
}
/* Else if current count is
equal to minimum count */
else if(count == minCount) {
/* Update the answer (to store
city with greater number) */
ans = i;
}
}
// Return the resulting city as answer
return ans;
}
public static void main(String[] args) {
int N = 4, M = 4;
int[][] edges = {
{0, 1, 3}, {1, 2, 1},
{1, 3, 4}, {2, 3, 1}
};
int distanceThreshold = 4;
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function to find the city with
the smallest number of neighbors. */
int ans = sol.findCity(N, M, edges, distanceThreshold);
// Output
System.out.println("The city with smallest number of neighbors (with given threshold) is: " + ans);
}
}
class Solution:
# Function to find the city with
# the smallest number of neighbors.
def findCity(self, n, m, edges, distanceThreshold):
# Adjacency matrix to store the graph
adjMat = [[1e9] * n for _ in range(n)]
# Filling up the adjacency matrix
for it in edges:
adjMat[it[0]][it[1]] = it[2]
adjMat[it[1]][it[0]] = it[2]
# Applying Floyd Warshall Algorithm
# For intermediate node k
for k in range(n):
# node i ---> node j
for i in range(n):
for j in range(n):
adjMat[i][j] = min(adjMat[i][j], adjMat[i][k] + adjMat[k][j])
# To store the minimum count of neighbors
minCount = int(1e9)
# To store the answer (city having
# smallest number of neighbors)
ans = -1
# Check every city
for i in range(n):
# To count the neighbors of given city
# having distance lesser than threshold
count = 0
# City i ---> City j
for j in range(n):
# If the distance to reach city j from
# city i is less than threshold
if i != j and adjMat[i][j] <= distanceThreshold:
# Increment count
count += 1
# if current count is less than minimum count
if count < minCount:
# Update minimum count
minCount = count
# Store the answer
ans = i
# Else if current count is
# equal to minimum count
elif count == minCount:
# Update the answer (to store
# city with greater number)
ans = i
# Return the resulting city as answer
return ans
# Main function to test the solution
if __name__ == "__main__":
N, M = 4, 4
edges = [
[0, 1, 3], [1, 2, 1],
[1, 3, 4], [2, 3, 1]
]
distanceThreshold = 4
# Creating an instance of
# Solution class
sol = Solution()
# Function to find the city with
# the smallest number of neighbors.
ans = sol.findCity(N, M, edges, distanceThreshold)
# Output
print("The city with smallest number of neighbors (with given threshold) is:", ans)
class Solution {
/* Function to find the city with
the smallest number of neighbors. */
findCity(n, m, edges, distanceThreshold) {
// Adjacency matrix to store the graph
let adjMat = Array.from({ length: n }, () => Array(n).fill(1e9));
// Filling up the adjacency matrix
for (let it of edges) {
adjMat[it[0]][it[1]] = it[2];
adjMat[it[1]][it[0]] = it[2];
}
// Applying Floyd Warshall Algorithm
// For intermediate node k
for (let k = 0; k < n; k++) {
// node i ---> node j
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
adjMat[i][j] =
Math.min(adjMat[i][j],
adjMat[i][k] + adjMat[k][j]
);
}
}
}
// To store the minimum count of neighbors
let minCount = 1e9;
/* To store the answer (city having
smallest number of neighbors) */
let ans;
// Check every city
for (let i = 0; i < n; i++) {
/* To count the neighbors of given city
having distance lesser than threshold */
let count = 0;
// City i ---> City j
for (let j = 0; j < n; j++) {
/* If the distance to reach city j from
city i is less than threshold */
if (i !== j && adjMat[i][j] <= distanceThreshold) {
// Increment count
count++;
}
}
// if current count is less than minimum count
if (count < minCount) {
// Update minimum count
minCount = count;
// Store the answer
ans = i;
}
/* Else if current count is
equal to minimum count */
else if (count === minCount) {
/* Update the answer (to store
city with greater number) */
ans = i;
}
}
// Return the resulting city as answer
return ans;
}
}
// Main function to test the solution
const main = () => {
const N = 4, M = 4;
const edges = [
[0, 1, 3], [1, 2, 1],
[1, 3, 4], [2, 3, 1]
];
const distanceThreshold = 4;
/* Creating an instance of
Solution class */
const sol = new Solution();
/* Function to find the city with
the smallest number of neighbors. */
const ans = sol.findCity(N, M, edges, distanceThreshold);
// Output
console.log("The city with smallest number of neighbors (with given threshold) is:", ans);
};
main();
Time Complexity: O(N3) (where N is the number of nodes(cities) in graph)
Space Complexity: O(N2)
The only space used is for the distance matrix taking O(N2) space and for a couple of variables taking O(1) space.
Q: Can there be multiple roads between the same cities?
A: If so, use the minimum weight among them when constructing the adjacency matrix.
Q: How do we handle cities that are unreachable?
A: If dist[i][j] > Threshold, city j is not considered reachable from i.
Q: What if edges had negative weights?
A: Bellman-Ford (O(n²m)) would be needed for negative weights, as Floyd-Warshall does not work with negative cycles.
Q: How would we handle dynamic graph changes (adding/removing edges)?
A: Use Dijkstra’s Algorithm on demand instead of recomputing all-pairs shortest paths.