-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path2359. Find Closest Node to Given Two Nodes 25 jan
49 lines (46 loc) · 1.43 KB
/
2359. Find Closest Node to Given Two Nodes 25 jan
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
class Solution {
public:
int closestMeetingNode(vector<int>& edges, int node1, int node2) {
std::vector<int> dist1(edges.size(), -1);
std::vector<int> dist2(edges.size(), -1);
// perform BFS from both nodes
std::queue<int> q;
q.push(node1);
dist1[node1] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
if (edges[u] != -1) {
if (dist1[edges[u]] == -1) {
dist1[edges[u]] = dist1[u] + 1;
q.push(edges[u]);
}
}
}
q.push(node2);
dist2[node2] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
if (edges[u] != -1) {
if (dist2[edges[u]] == -1) {
dist2[edges[u]] = dist2[u] + 1;
q.push(edges[u]);
}
}
}
// find the node that can be reached from both nodes with the minimum maximum distance
int minDist = INT_MAX;
int minNode = -1;
for (int i = 0; i < edges.size(); i++) {
if (dist1[i] != -1 && dist2[i] != -1) {
int maxDist = std::max(dist1[i], dist2[i]);
if (maxDist < minDist) {
minDist = maxDist;
minNode = i;
}
}
}
return minNode;
}
};