[LeetCode] Find Closest Node to Given Two Nodes

2359. Find Closest Node to Given Two Nodes

You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1.

You are also given two integers node1 and node2.

Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1.

Note that edges may contain cycles.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
void dfs(int u, int d, vector<long long>& dis, vector<int>& adj) {
if(dis[u] < d) return;
dis[u] = d;
if(adj[u] != -1)
dfs(adj[u], d + 1, dis, adj);
}
public:
int closestMeetingNode(vector<int>& edges, int node1, int node2) {
int n = edges.size();
vector<long long> dis1(n, 1ll * INT_MAX * 10), dis2(n, 1ll * INT_MAX * 10);
dfs(node1, 0, dis1, edges);
dfs(node2, 0, dis2, edges);

long long distance = INT_MAX, res = -1;
for(int i = 0; i < n; i++) {
if(max(dis1[i],dis2[i]) < distance) {
distance = max(dis1[i],dis2[i]);
res = i;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/31/PS/LeetCode/find-closest-node-to-given-two-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.