-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfind_city.cpp
55 lines (54 loc) · 1.54 KB
/
find_city.cpp
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
class Solution {
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
// floyd warshall algorithm
/*
computes shortest distance between any two vertex in graph
O(V^3)
consider each vertex as intermediate node and check shortest distance
*/
vector <vector<int>> distance(n,vector <int> (n,100000));
for(int i=0;i<edges.size();i++)
{
int from = edges[i][0];
int to = edges[i][1];
int weight = edges[i][2];
distance[from][to] = distance[to][from] = weight;
}
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
if(distance[i][j] > distance[i][k] + distance[k][j])
distance[i][j] = distance[i][k] + distance[k][j];
}
}
}
}
int city;
int min_count = INT_MAX;
for(int i=0;i<n;i++)
{
int count = 0;
for(int j=0;j<n;j++)
{
// cout<<distance[i][j]<<" ";
if(distance[i][j] <= distanceThreshold)
{
count++;
}
}
// cout<<count<<endl;
if(count <= min_count)
{
min_count = count;
city = i;
}
}
return city;
}
};