forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind Eventual Safe States.py
39 lines (31 loc) · 975 Bytes
/
Find Eventual Safe States.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import collections
class Solution:
def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:
n = len(graph)
ans = []
for i in range(n):
if not graph[i]:
ans.append(i)
def loop(key, loops):
loops.append(key)
for i in graph[key]:
if i in loops:
return False
elif i in ans:
continue
else:
r = loop(i, loops)
if r == True:
continue
else:
return False
idx = loops.index(key)
loops.pop(idx)
return True
for i in range(n):
loops = []
if i in ans:
continue
r = loop(i, loops)
if r == True: ans.append(i)
return sorted(ans)