1
+ # Runtime: 2578 ms (Top 92.45%) | Memory: 69.3 MB (Top 19.78%)
1
2
class Solution :
2
3
def networkBecomesIdle (self , edges : List [List [int ]], patience : List [int ]) -> int :
3
-
4
+
4
5
#Build Adjency List
5
6
adjList = defaultdict (list )
6
-
7
+
7
8
for source , target in edges :
8
9
adjList [source ].append (target )
9
10
adjList [target ].append (source )
10
-
11
-
11
+
12
12
#BFS to get the shortest route from node to master.
13
13
shortest = {}
14
14
queue = deque ([(0 ,0 )])
15
15
seen = set ()
16
16
while queue :
17
17
currPos , currDist = queue .popleft ()
18
-
18
+
19
19
if currPos in seen :
20
20
continue
21
21
seen .add (currPos )
22
22
shortest [currPos ] = currDist
23
-
23
+
24
24
for nei in adjList [currPos ]:
25
25
queue .append ((nei , currDist + 1 ))
26
26
27
-
28
27
#Calculate answer using shortest paths.
29
28
ans = 0
30
29
for index in range (1 ,len (patience )):
31
30
resendInterval = patience [index ]
32
-
31
+
33
32
#The server will stop sending requests after it's been sent to the master node and back.
34
33
shutOffTime = (shortest [index ] * 2 )
35
-
34
+
36
35
# shutOffTime-1 == Last second the server can send a re-request.
37
36
lastSecond = shutOffTime - 1
38
-
37
+
39
38
#Calculate the last time a packet is actually resent.
40
39
lastResentTime = (lastSecond // resendInterval )* resendInterval
41
-
40
+
42
41
# At the last resent time, the packet still must go through 2 more cycles to the master node and back.
43
42
lastPacketTime = lastResentTime + shutOffTime
44
-
43
+
45
44
ans = max (lastPacketTime , ans )
46
-
45
+
47
46
#Add +1, the current answer is the last time the packet is recieved by the target server (still active).
48
47
#We must return the first second the network is idle, therefore + 1
49
- return ans + 1
48
+ return ans + 1
0 commit comments