Skip to content

Commit 399e0c0

Browse files
authored
Create 2359. Find Closest Node to Given Two Nodes (#808)
2 parents 0f87c75 + fed34fe commit 399e0c0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public:
3+
vector<int> bfs(const vector<int>& edges, int start) {
4+
int n = edges.size();
5+
vector<int> dist(n, -1);
6+
queue<int> q;
7+
q.push(start);
8+
dist[start] = 0;
9+
10+
while (!q.empty()) {
11+
int node = q.front();
12+
q.pop();
13+
14+
int next = edges[node];
15+
if (next != -1 && dist[next] == -1) {
16+
dist[next] = dist[node] + 1;
17+
q.push(next);
18+
}
19+
}
20+
return dist;
21+
}
22+
23+
int closestMeetingNode(vector<int>& edges, int node1, int node2) {
24+
vector<int> dist1 = bfs(edges, node1);
25+
vector<int> dist2 = bfs(edges, node2);
26+
27+
int minDist = INT_MAX, res = -1;
28+
for (int i = 0; i < edges.size(); ++i) {
29+
if (dist1[i] != -1 && dist2[i] != -1) {
30+
int maxDist = max(dist1[i], dist2[i]);
31+
if (maxDist < minDist) {
32+
minDist = maxDist;
33+
res = i;
34+
}
35+
}
36+
}
37+
return res;
38+
}
39+
};

0 commit comments

Comments
 (0)