Skip to content

Commit dc5cbd6

Browse files
authored
Create 1334. Find the City With the Smallest Number of Neighbors at a… (#538)
2 parents 45a22c2 + 8f592d5 commit dc5cbd6

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
void dijsktra(int src,vector<vector<pair<int,int>>> &adj,vector<vector<int>> &dist){
3+
priority_queue<pair<int,int>> pq;
4+
dist[src][src]=0;
5+
pq.push({0,src});
6+
pair<int,int> crr;
7+
int d;
8+
while(!pq.empty()){
9+
crr= pq.top();
10+
pq.pop();
11+
for(auto &node:adj[crr.second]){
12+
if((-1*crr.first) + node.second<=dist[src][node.first]){
13+
d= (-1*crr.first)+node.second;
14+
dist[src][node.first]=d;
15+
pq.push({-1*d,node.first});
16+
}
17+
}
18+
}
19+
}
20+
public:
21+
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
22+
vector<vector<pair<int,int>>> adj(n);
23+
for(auto &edge:edges){
24+
adj[edge[0]].push_back({edge[1],edge[2]});
25+
adj[edge[1]].push_back({edge[0],edge[2]});
26+
}
27+
vector<vector<int>> dist(n,vector<int> (n,INT_MAX));
28+
for(int i=0;i<n;i++){
29+
dijsktra(i,adj,dist);
30+
}
31+
int res=-1,count,minCount=INT_MAX;
32+
for(int i=0;i<n;i++){
33+
count=0;
34+
for(int j=0;j<n;j++){
35+
if(i!=j && dist[i][j]<=distanceThreshold)count++;
36+
}
37+
if(count<=minCount){
38+
minCount=count;
39+
res=i;
40+
}
41+
}
42+
return res;
43+
}
44+
};

0 commit comments

Comments
 (0)