2359: Find-Closest-Node-to-Given-Two-Nodes
Medium
Basically, from each starting node, iterate through all the
nodes you have not seen before, updating their
distance as you go. Since some distances will not be updated, we
can leave them as -1
.
Then, you can iterate through all the nodes, ignoring the
ones with distance -1
, finding the
minimum index of the node, where the
maximum distance between node1
to
that node and node2
to that node is
minimized.
Example:
Index | Node 1 | Node 2
------|--------|-------
0 | 1 | 3
1 | 5 | 1
2 | 4 | 0
3 | 0 | 2
4 | 3 | 5
5 | 2 | 4 6 | -1 | -1
In this case, you would choose index 3
since you
minimize the maximum distance between itself and
node1
& node2
.
Code:
class Solution {
public:
int closestMeetingNode(vector<int>& edges, int node1, int node2) {
<int, int> ans = {INT32_MAX, INT32_MAX};
pair<bool> seen(edges.size(), false);
vector<pair<int, int>> distances(edges.size(), {-1, -1});
vector[node1].first = 0;
distances[node2].second = 0;
distances
int distance = 1;
while (node1 != -1 && !seen[node1]) {
[node1] = true;
seen= edges[node1];
node1
if (node1 != -1) {
if (!seen[node1]) {
[node1].first = distance++;
distances}
}
}
(seen.begin(), seen.end(), false);
fill
= 1;
distance while (node2 != -1 && !seen[node2]) {
[node2] = true;
seen= edges[node2];
node2
if (node2 != -1) {
if (!seen[node2]) {
[node2].second = distance++;
distances}
}
}
for (int i = 0; i < edges.size(); ++i) {
if (distances[i].first >= 0 && distances[i].second >= 0) {
int max_distance = max(distances[i].first, distances[i].second);
if (max_distance < ans.second || (max_distance == ans.second && i < ans.first)) {
= {i, max_distance};
ans }
}
}
return ans.first == INT32_MAX ? -1 : ans.first;
}
};