IT/Computer Science
[Leetcode/Graph, Depth-First Search(DFS)] 2359. Find Closest Node to Given Two Nodes
Diana Kang
2025. 5. 31. 05:35
class Solution:
def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:
def trace_path(start):
dist = {}
step = 0
while start != -1 and start not in dist:
dist[start] = step
step += 1
start = edges[start]
return dist
dist1 = trace_path(node1)
dist2 = trace_path(node2)
result = -1
min_dist = float('inf')
for node in range(len(edges)):
if node in dist1 and node in dist2:
max_dist = max(dist1[node], dist2[node])
if max_dist < min_dist:
min_dist = max_dist
result = node
return result
- float('inf'): positive infinity
- a special floating-point value that’s larger than any real number.
- step += 1
- In the line step += 1, the variable step is keeping track of the number of steps (or distance) taken from the starting node to reach each subsequent node.