Skip to content

Latest commit

 

History

History
42 lines (35 loc) · 1.33 KB

2023-01-25.md

File metadata and controls

42 lines (35 loc) · 1.33 KB

题目

  1. 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.

思路

代码

var closestMeetingNode = function(edges, node1, node2) {
  function dfs(node, memo) {
    let distance = 0
    while (node != -1 && memo[node] == undefined) {
      memo[node] = distance++
      node = edges[node]
    }
  }
  const m1 = {}
  const m2 = {}
  dfs(node1, m1)
  dfs(node2, m2)
  let res = -1
  let min = Number.MAX_SAFE_INTEGER;
  for (let i = 0; i < edges.length; i++) {
    if (m1[i] == undefined || m2[i] == undefined) continue
    const max = Math.max(m1[i], m2[i])
    if (max < min) {
      min = max
      res = i
    }
  }
  return res
}