Given a graph with n nodes and m edges, each edges[i] = [u, v, weight] and d as the maximum distance to reach the neighbor nodes, the task is to find the total number of nodes with maximum reachable neighbors.
Input: n = 4, edges = [[0, 1, 3], [1, 2, 1], [1, 3, 4], [2, 3, 1]], d = 4
Output: 2
Explanation: node 0 -> [node 1, node 2]
node 1 -> [node 0, node 2, node 3]
node 2 -> [node 0, node 1, node 3]
node 3 -> [node 1, node 2]These are the nodes that are reachable with a maximum distance of d. Thereby out of these node1 and node2 can reach maximum neighbors (3 neighbors). So the answer is node1 and node2, i.e. 2. As we need to return the count of the total number of such nodes.
Approach: To solve the problem follow the below observations:
Here in the above graph, We can observe that Node 1 and 2 can reach to maximum no. of neighbors (here it is all the 3 other nodes). So total there 2 number of nodes that can reach the maximum no. of neighbors (here it is 3) with a limited distance of d (here it is 4).
Follow the below steps to solve the above approach:
- Create an adjacency list for the given graph.
- Run the Floyd warshall algorithm to find all sources shortest distance.
- Then iterate for every node against every adjacent node.
- Count the number of adjacent nodes that are reachable with less than or equal to distance d.
- Then, have a separate count of answers and maxCount (Maximum neighbors), comparing to it increment the answer counter.
Below is the Implementation of the above approach:
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std;
int findTheCity( int n, vector<vector< int > >& edges, int d)
{ // 2D matrix n*n
vector<vector< int > > dist(n, vector< int >(n, 1e9));
for ( auto e : edges) {
// nodes
int u = e[0];
int v = e[1];
int d = e[2];
// edge wt
// bidirectional edges u-v and v-u
dist[u][v] = d;
dist[v][u] = d;
}
for ( int i = 0; i < n; i++) {
// Self loops
dist[i][i] = 0;
}
// Floyd Warshall Algo
for ( int k = 0; k < n; k++) {
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
dist[i][j] = min(dist[i][j],
dist[i][k] + dist[k][j]);
}
}
}
// To store the maximum neighbors
// possible
int maxCtr = INT_MIN;
// Stores the count of total such nodes
// having max neighbours with
// atmax d distance
int ansctr = 0;
for ( int node = 0; node < n; node++) {
// How many neighbours within limit
// for that node
int ctr = 0;
for ( int adjNode = 0; adjNode < n; adjNode++) {
if (dist[node][adjNode] <= d) {
ctr++;
}
}
if (ctr > maxCtr) {
// Update as we got a node that
// has higher neighbours
maxCtr = ctr;
ansctr = 1;
}
// Equal to max, so increment counter
// as of now this is the max
else if (ctr == maxCtr)
ansctr++;
}
return ansctr;
} // Driver Code int main()
{ // edges [u, v, wt]
vector<vector< int > > edges = {
{ 0, 1, 3 }, { 1, 2, 1 }, { 1, 3, 4 }, { 2, 3, 1 }
};
// Maximum distance to reach the neighbour
int d = 4;
// Number of nodes in graph
int n = 4;
int ans = findTheCity(n, edges, d);
cout << ans << "\n" ;
return 0;
} |
// Java code for the above approach: import java.util.*;
public class Main {
static int findTheCity( int n, int [][] edges, int d)
{
// 2D matrix n*n
int [][] dist = new int [n][n];
for ( int i = 0 ; i < n; i++) {
Arrays.fill(dist[i], Integer.MAX_VALUE / 2 );
// Self loops
dist[i][i] = 0 ;
}
for ( int [] e : edges) {
// edge wt
// bidirectional edges u-v and v-u
int u = e[ 0 ], v = e[ 1 ], w = e[ 2 ];
dist[u][v] = dist[v][u] = w;
}
// Floyd Warshall Algo
for ( int k = 0 ; k < n; k++) {
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < n; j++) {
dist[i][j]
= Math.min(dist[i][j],
dist[i][k] + dist[k][j]);
}
}
}
int maxCtr = Integer.MIN_VALUE;
// Stores the count of total such nodes
// having max neighbours with
// atmax d distance
int ansctr = 0 ;
for ( int node = 0 ; node < n; node++) {
int ctr = 0 ;
// How many neighbours within limit
// for that node
for ( int adjNode = 0 ; adjNode < n; adjNode++) {
if (dist[node][adjNode] <= d) {
ctr++;
}
}
if (ctr > maxCtr) {
// Update as we got a node that
// has higher neighbours
maxCtr = ctr;
ansctr = 1 ;
} // Equal to max, so increment counter
// as of now this is the max
else if (ctr == maxCtr) {
ansctr++;
}
}
return ansctr;
}
// Driver Code
public static void main(String[] args)
{
// edges [u, v, wt]
int [][] edges = { { 0 , 1 , 3 },
{ 1 , 2 , 1 },
{ 1 , 3 , 4 },
{ 2 , 3 , 1 } };
// Maximum distance to reach the neighbour
int d = 4 ;
// Number of nodes in graph
int n = 4 ;
int ans = findTheCity(n, edges, d);
System.out.println(ans);
}
} |
from typing import List
def find_the_city(n: int , edges: List [ List [ int ]], d: int ) - > int :
# Initialize a 2D list "dist" to store the distances between the nodes
# Set all distances to 1e9 (a large value)
dist = [[ 1e9 ] * n for _ in range (n)]
# Set the distance between the nodes connected by an
# edge to the weight of the edge
for u, v, wt in edges:
dist[u][v] = wt
dist[v][u] = wt
# Set the distance between a node and itself to 0
for i in range (n):
dist[i][i] = 0
# Use the Floyd Warshall algorithm to find the shortest
# distances between all pairs of nodes
for k in range (n):
for i in range (n):
for j in range (n):
dist[i][j] = min (dist[i][j], dist[i][k] + dist[k][j])
# Initialize "max_ctr" to the minimum possible value
max_ctr = float ( '-inf' )
# Initialize "ans_ctr" to 0
ans_ctr = 0
# Iterate through each node
for node in range (n):
# Initialize a counter "ctr" to count the number of
# neighbors within the maximum distance "d"
ctr = 0
# Iterate through each adjacent node
for adj_node in range (n):
# If the distance between the current node and the
# adjacent node is less than or equal to "d",
# increment the counter
if dist[node][adj_node] < = d:
ctr + = 1
# If the number of neighbors is greater than the
# current maximum number of neighbors,
# update "max_ctr" and set "ans_ctr" to 1
if ctr > max_ctr:
max_ctr = ctr
ans_ctr = 1
# If the number of neighbors is equal to the
# current maximum number of neighbors,
# increment "ans_ctr"
elif ctr = = max_ctr:
ans_ctr + = 1
# Return the final result
return ans_ctr
# Driver Code d = 4
n = 4
edges = [[ 0 , 1 , 3 ], [ 1 , 2 , 1 ], [ 1 , 3 , 4 ], [ 2 , 3 , 1 ]]
print (find_the_city(d,edges,n))
#This code is contributed by Potta Lokesh |
function findTheCity(n, edges, d) {
// 2D matrix n*n
let dist = new Array(n).fill(0).map(() => new Array(n).fill(Number.MAX_VALUE));
for (let i = 0; i < edges.length; i++) {
// nodes
let u = edges[i][0];
let v = edges[i][1];
let w = edges[i][2];
// edge wt
// bidirectional edges u-v and v-u
dist[u][v] = w;
dist[v][u] = w;
}
for (let i = 0; i < n; i++) {
// Self loops
dist[i][i] = 0;
}
// Floyd Warshall Algo
for (let k = 0; k < n; k++) {
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
dist[i][j] = Math.min(dist[i][j],
dist[i][k] + dist[k][j]);
}
}
}
// To store the maximum neighbors
// possible
let maxCtr = Number.MIN_SAFE_INTEGER;
// Stores the count of total such nodes
// having max neighbours with
// atmax d distance
let ansctr = 0;
for (let node = 0; node < n; node++) {
// How many neighbours within limit
// for that node
let ctr = 0;
for (let adjNode = 0; adjNode < n; adjNode++) {
if (dist[node][adjNode] <= d) {
ctr++;
}
}
if (ctr > maxCtr) {
// Update as we got a node that
// has higher neighbours
maxCtr = ctr;
ansctr = 1;
}
// Equal to max, so increment counter
// as of now this is the max
else if (ctr === maxCtr)
ansctr++;
}
return ansctr;
} // Example usage: // edges [u, v, wt] let edges = [ [0, 1, 3], [1, 2, 1], [1, 3, 4], [2, 3, 1]
]; // Maximum distance to reach the neighbour let d = 4; // Number of nodes in graph let n = 4; let ans = findTheCity(n, edges, d); console.log(ans); |
using System;
public class MainClass
{ static int FindTheCity( int n, int [][] edges, int d)
{
// 2D matrix n*n
int [][] dist = new int [n][];
for ( int i = 0; i < n; i++) {
dist[i] = new int [n];
Array.Fill(dist[i], int .MaxValue / 2);
// Self loops
dist[i][i] = 0;
}
for ( int i = 0; i < edges.Length; i++) {
// edge wt
// bidirectional edges u-v and v-u
int u = edges[i][0], v = edges[i][1], w = edges[i][2];
dist[u][v] = dist[v][u] = w;
}
// Floyd Warshall Algo
for ( int k = 0; k < n; k++) {
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
dist[i][j]
= Math.Min(dist[i][j],
dist[i][k] + dist[k][j]);
}
}
}
int maxCtr = int .MinValue;
// Stores the count of total such nodes
// having max neighbours with
// atmax d distance
int ansctr = 0;
for ( int node = 0; node < n; node++) {
int ctr = 0;
// How many neighbours within limit
// for that node
for ( int adjNode = 0; adjNode < n; adjNode++) {
if (dist[node][adjNode] <= d) {
ctr++;
}
}
if (ctr > maxCtr) {
// Update as we got a node that
// has higher neighbours
maxCtr = ctr;
ansctr = 1;
} // Equal to max, so increment counter
// as of now this is the max
else if (ctr == maxCtr) {
ansctr++;
}
}
return ansctr;
}
public static void Main()
{
// edges [u, v, wt]
int [][] edges = { new int [] { 0, 1, 3 },
new int [] { 1, 2, 1 },
new int [] { 1, 3, 4 },
new int [] { 2, 3, 1 } };
// Maximum distance to reach the neighbour
int d = 4;
// Number of nodes in graph
int n = 4;
int ans = FindTheCity(n, edges, d);
Console.WriteLine(ans);
}
} |
2
Time Complexity: O(M) + O(N^3) + O(N^2) = O(N^3) Dominant factor
- O(M) = O(N^2) as at max edges can be N^2
- O(N^3) Floyd warshall algorithm takes
- O(N^2) To find out the count of such nodes.
Auxiliary Space Complexity: O(N+M) + O(N^2)
- O(N+M) the adjacency list takes as such
- O(N^2) the distance 2D Vector / Matrix
Related Articles: