|
| 1 | +# Runtime: 3032 ms (Top 5.02%) | Memory: 139.1 MB (Top 14.52%) |
1 | 2 | class Solution:
|
2 | 3 | def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:
|
3 |
| - |
| 4 | + |
4 | 5 | res = float("inf")
|
5 |
| - |
| 6 | + |
6 | 7 | def dfs(node, arr, counter=0):
|
7 |
| - |
8 |
| - #making sure we haven't visited the node before (i.e., value in the array != -1) |
| 8 | + |
| 9 | + #making sure we haven't visited the node before (i.e., value in the array != -1) |
9 | 10 | while arr[node]==-1 and node!=-1:
|
10 |
| - |
11 |
| - #assigning how many moves it takes to reach node |
| 11 | + |
| 12 | + #assigning how many moves it takes to reach node |
12 | 13 | arr[node] = counter
|
13 | 14 | next_node = edges[node]
|
14 |
| - |
15 |
| - #going through each neighbor if exists and updating the counter |
| 15 | + |
| 16 | + #going through each neighbor if exists and updating the counter |
16 | 17 | dfs(edges[node], arr, counter+1)
|
17 | 18 |
|
18 | 19 | return arr
|
19 |
| - |
20 |
| - #find moves to reach nodes from node1 |
| 20 | + |
| 21 | + #find moves to reach nodes from node1 |
21 | 22 | n1 = [-1 for i in range(len(edges))]
|
22 | 23 | dfs(node1, n1)
|
23 |
| - |
24 |
| - #find moves to reach nodes from node2 |
| 24 | + |
| 25 | + #find moves to reach nodes from node2 |
25 | 26 | n2 = [-1 for i in range(len(edges))]
|
26 | 27 | dfs(node2, n2)
|
27 |
| - |
| 28 | + |
28 | 29 | answer = -1
|
29 |
| - |
| 30 | + |
30 | 31 | for i in range(len(edges)):
|
31 |
| - |
32 |
| - #check if the end node is reachable from both starting nodes |
| 32 | + |
| 33 | + #check if the end node is reachable from both starting nodes |
33 | 34 | if n1[i]!=-1 and n2[i]!=-1:
|
34 | 35 | maximum_distance = max(n1[i], n2[i])
|
35 |
| - |
36 |
| - #update the distance and the final answer if relevant |
| 36 | + |
| 37 | + #update the distance and the final answer if relevant |
37 | 38 | if maximum_distance<res:
|
38 | 39 | res = maximum_distance
|
39 | 40 | answer = i
|
40 |
| - |
| 41 | + |
41 | 42 | return answer
|
42 |
| - |
0 commit comments