From fed34fec1bf8f3c3f67efa7572d04e8911a83e57 Mon Sep 17 00:00:00 2001 From: chayan das Date: Fri, 30 May 2025 21:57:41 +0530 Subject: [PATCH] Create 2359. Find Closest Node to Given Two Nodes --- 2359. Find Closest Node to Given Two Nodes | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 2359. Find Closest Node to Given Two Nodes diff --git a/2359. Find Closest Node to Given Two Nodes b/2359. Find Closest Node to Given Two Nodes new file mode 100644 index 0000000..afe1b1f --- /dev/null +++ b/2359. Find Closest Node to Given Two Nodes @@ -0,0 +1,39 @@ +class Solution { +public: + vector bfs(const vector& edges, int start) { + int n = edges.size(); + vector dist(n, -1); + queue 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& edges, int node1, int node2) { + vector dist1 = bfs(edges, node1); + vector 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; + } +};