Sponsored
Sponsored
We can perform a Breadth-First Search (BFS) from both node1 and node2 to compute shortest distances to all other nodes. Since BFS is useful for finding shortest paths in unweighted graphs, it suits our needs in this problem.
By storing distances from both starting nodes in separate arrays and iterating through all nodes, we can find the node minimizing the maximum of both distances.
Time Complexity: O(n) since each node is processed in the queue at most once.
Space Complexity: O(n) for storing distances.
1#include <vector>
2#include <queue>
3#include <algorithm>
4#include <limits.h>
5
6class Solution {
7public:
8 std::vector<int> bfs(const std::vector<int>& edges, int start) {
9 int n = edges.size();
10 std::vector<int> dist(n, -1);
11 std::queue<int> q;
12 q.push(start);
13 dist[start] = 0;
14 while (!q.empty()) {
15 int node = q.front();
16 q.pop();
17 int nextNode = edges[node];
18 if (nextNode != -1 && dist[nextNode] == -1) {
19 dist[nextNode] = dist[node] + 1;
20 q.push(nextNode);
21 }
22 }
23 return dist;
24 }
25
26 int closestMeetingNode(std::vector<int>& edges, int node1, int node2) {
27 int n = edges.size();
28 auto dist1 = bfs(edges, node1);
29 auto dist2 = bfs(edges, node2);
30
31 int minDist = INT_MAX;
32 int result = -1;
33 for (int i = 0; i < n; ++i) {
34 if (dist1[i] != -1 && dist2[i] != -1) {
35 int maxDist = std::max(dist1[i], dist2[i]);
36 if (maxDist < minDist) {
37 minDist = maxDist;
38 result = i;
39 }
40 }
41 }
42 return result;
43 }
44};
This C++ solution follows the BFS strategy to determine the shortest path from both nodes to all reachable nodes and calculates the optimal meeting node minimizing the maximum distance.
Depth-First Search (DFS) can be leveraged to explore the graph while marking visited nodes to avoid cycles. This approach tracks distances from node1 and node2 in separate arrays, similarly to BFS but engages DFS mechanics.
Time Complexity: O(n) since every node is processed once.
Space Complexity: O(n) for the distance and visited sets.
1var
This JavaScript solution utilizes DFS to trace paths from both nodes while avoiding cycles. The comparison of path distances enables determining the suitable meeting node.