Skip to content

Create 2359. Find Closest Node to Given Two Nodes #808

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 31, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions 2359. Find Closest Node to Given Two Nodes
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
public:
vector<int> bfs(const vector<int>& edges, int start) {
int n = edges.size();
vector<int> dist(n, -1);
queue<int> q;
q.push(start);
dist[start] = 0;

while (!q.empty()) {
int node = q.front();
q.pop();

int next = edges[node];
if (next != -1 && dist[next] == -1) {
dist[next] = dist[node] + 1;
q.push(next);
}
}
return dist;
}

int closestMeetingNode(vector<int>& edges, int node1, int node2) {
vector<int> dist1 = bfs(edges, node1);
vector<int> dist2 = bfs(edges, node2);

int minDist = INT_MAX, res = -1;
for (int i = 0; i < edges.size(); ++i) {
if (dist1[i] != -1 && dist2[i] != -1) {
int maxDist = max(dist1[i], dist2[i]);
if (maxDist < minDist) {
minDist = maxDist;
res = i;
}
}
}
return res;
}
};
Loading