1+ class Solution {
2+ public:
3+ int closestMeetingNode (vector<int >& edges, int node1, int node2) {
4+ int n = edges.size ();
5+ vector<vector<int >> adj (n);
6+
7+ // some of the destination nodes can be -1
8+ // it would also get added in the distance map in bfs traversal
9+ // it won't affect our result because we are traversing
10+ // from 0 to n indexes only
11+ for (int i=0 ; i<edges.size (); i++) {
12+ adj[i].push_back (edges[i]);
13+ }
14+
15+ unordered_map<int , int > node1Dist; // map node -> distance from node1
16+ unordered_map<int , int > node2Dist; // map node -> distance fromm node2
17+
18+ bfs (node1, node1Dist, adj);
19+ bfs (node2, node2Dist, adj);
20+
21+ int res = -1 ;
22+ int resDist = INT_MAX ;
23+
24+ for (int i=0 ; i<n; i++) {
25+ if (node1Dist.count (i) && node2Dist.count (i)) {
26+ dist = max (node1Dist[i] node2Dist[i]);
27+ if (dist < resDist) { // we have to take the smallest distance node and return the result node
28+ res = i;
29+ resDist = dist;
30+ }
31+ }
32+ }
33+ return res;
34+ }
35+
36+ void bfs (int src, unordered_map<int , int > distMap, vector<vector<int >> &adj) {
37+ queue<pair<int , int >> q;
38+ q.push ({src, 0 });
39+ distMap[src] = 0 ;
40+ while (!q.empty ()) {
41+ auto temp = q.front ();
42+ int node = temp.first ;
43+ int dist = temp.second ;
44+
45+ for (auto &nei: adj[node]) {
46+ if (distMap.find (i) == distMap.end ()) {
47+ q.push ({nei, dist + 1 });
48+ distMap[nei] = dist + 1 ;
49+ }
50+ }
51+ }
52+ }
53+ };
0 commit comments