1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance- Step by step approach

Noobnoob
2 min readApr 7, 2021

Question Link: here

Okay, so for this, we need to find out the cost to reach each node from a given node. For this, I will be using a 2D array that will have the cost as the entry and the row and column will be the nodes.

for eg. in 2D array, arr[1][2] will have the minimum cost to reach 2nd index city from 1st index city(starting with 0).

To calculate the cost, we will use the Floyd Warshell algorithm. Here is a link for the YT video to understand better this logic.

Once we have the 2D array, it will be very easy to go through each row and get the minimum of the cities with the cost lower than the threshold.

Here is my code.

class Solution {
public int findTheCity(int n, int[][] edges, int distanceThreshold) {
int[][] costMatrix=new int[n][n];
Arrays.stream(costMatrix).forEach(a -> Arrays.fill(a, Integer.MAX_VALUE/2));
for (int i = 0; i < n; i++) {
costMatrix[i][i]=0;
}
//calculating initial cost matrix using the input for (int[] arr:edges
) {
costMatrix[arr[0]][arr[1]]=arr[2];
costMatrix[arr[1]][arr[0]]=arr[2];
}
//Floyd-Warshall algo
for(int k = 0; k<n; k++) {
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
if(costMatrix[i][k]+costMatrix[k][j] < costMatrix[i][j])
costMatrix[i][j] = costMatrix[i][k]+costMatrix[k][j];
}
//taking the smallest number
int smallestCity = n;
int cityValue=0;
for (int i=0;i<n;i++
) {
int response=getSmallest(costMatrix[i],distanceThreshold);
if(response==0){
continue;
}
if(response<=smallestCity){
smallestCity=response;
cityValue=i;
}
}
return cityValue;
}
private static int getSmallest(int[] arr, int distanceThreshold) {
int counter = -1;
for (int cost:arr
) {
if(cost<=distanceThreshold){
counter++;
}
}
return counter;
}
}

Even after this, one of the test cases failed. I am not able to understand why.

Maybe you can help me with this? I am sure that 5 is not expected because there is no connection to the 5th city from any city.

--

--