2359. Find Closest Node to Given Two Nodes Medium
1/**
2 * [2359] Find Closest Node to Given Two Nodes
3 *
4 * You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.
5 * 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.
6 * You are also given two integers node1 and node2.
7 * 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.
8 * Note that edges may contain cycles.
9 *
10 * Example 1:
11 * <img alt="" src="https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-2.png" style="width: 321px; height: 161px;" />
12 * Input: edges = [2,2,3,-1], node1 = 0, node2 = 1
13 * Output: 2
14 * Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.
15 * The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.
16 *
17 * Example 2:
18 * <img alt="" src="https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-4.png" style="width: 195px; height: 161px;" />
19 * Input: edges = [1,2,-1], node1 = 0, node2 = 2
20 * Output: 2
21 * Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.
22 * The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.
23 *
24 *
25 * Constraints:
26 *
27 * n == edges.length
28 * 2 <= n <= 10^5
29 * -1 <= edges[i] < n
30 * edges[i] != i
31 * 0 <= node1, node2 < n
32 *
33 */
34pub struct Solution {}
35
36// problem: https://leetcode.com/problems/find-closest-node-to-given-two-nodes/
37// discuss: https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/?currentPage=1&orderBy=most_votes&query=
38
39// submission codes start here
40
41impl Solution {
42 pub fn closest_meeting_node(edges: Vec<i32>, node1: i32, node2: i32) -> i32 {
43 0
44 }
45}
46
47// submission codes end
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn test_2359() {
55 }
56}
57
Back
© 2025 bowen.ge All Rights Reserved.