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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int[] Bfs(int[] edges, int start) {
6 int n = edges.Length;
7 int[] dist = new int[n];
8 Array.Fill(dist, -1);
9 Queue<int> queue = new Queue<int>();
10 queue.Enqueue(start);
11 dist[start] = 0;
12 while (queue.Count > 0) {
13 int node = queue.Dequeue();
14 int nextNode = edges[node];
15 if (nextNode != -1 && dist[nextNode] == -1) {
16 dist[nextNode] = dist[node] + 1;
17 queue.Enqueue(nextNode);
18 }
19 }
20 return dist;
21 }
22
23 public int ClosestMeetingNode(int[] edges, int node1, int node2) {
24 int n = edges.Length;
25 int[] dist1 = Bfs(edges, node1);
26 int[] dist2 = Bfs(edges, node2);
27
28 int minDist = int.MaxValue;
29 int result = -1;
30 for (int i = 0; i < n; i++) {
31 if (dist1[i] != -1 && dist2[i] != -1) {
32 int maxDist = Math.Max(dist1[i], dist2[i]);
33 if (maxDist < minDist) {
34 minDist = maxDist;
35 result = i;
36 }
37 }
38 }
39 return result;
40 }
41}
The C# solution leverages BFS to compute shortest distances from two nodes. It then compares these to find the node that minimizes the maximum travel distance, effectively handling graphs efficiently.
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.