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.
1import java.util.*;
2
3class Solution {
4 public int[] bfs(int[] edges, int start) {
5 int n = edges.length;
6 int[] dist = new int[n];
7 Arrays.fill(dist, -1);
8 Queue<Integer> queue = new LinkedList<>();
9 queue.add(start);
10 dist[start] = 0;
11 while (!queue.isEmpty()) {
12 int node = queue.poll();
13 int nextNode = edges[node];
14 if (nextNode != -1 && dist[nextNode] == -1) {
15 dist[nextNode] = dist[node] + 1;
16 queue.add(nextNode);
17 }
18 }
19 return dist;
20 }
21
22 public int closestMeetingNode(int[] edges, int node1, int node2) {
23 int n = edges.length;
24 int[] dist1 = bfs(edges, node1);
25 int[] dist2 = bfs(edges, node2);
26
27 int minDist = Integer.MAX_VALUE;
28 int result = -1;
29 for (int i = 0; i < n; i++) {
30 if (dist1[i] != -1 && dist2[i] != -1) {
31 int maxDist = Math.max(dist1[i], dist2[i]);
32 if (maxDist < minDist) {
33 minDist = maxDist;
34 result = i;
35 }
36 }
37 }
38 return result;
39 }
40}
The Java solution employs BFS to compute shortest paths from both nodes and identifies the suitable node minimizing maximal distance. This approach balances readability and efficiency.
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.
1class
This Python solution uses DFS to explore graphs from two nodes, calculating visiting distances and determining the optimal meeting node that minimizes the maximal distance.