File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## Find Eventual Safe States
2
+
3
+ #### Description
4
+
5
+ [ link] ( https://leetcode.com/problems/find-eventual-safe-states/ )
6
+
7
+ ---
8
+
9
+ #### Solution
10
+
11
+ - See Code
12
+
13
+ ---
14
+
15
+ #### Code
16
+
17
+ > 最坏情况:O(n^2)
18
+
19
+ ``` python
20
+ class Solution :
21
+ def eventualSafeNodes (self , graph : List[List[int ]]) -> List[int ]:
22
+ visited = [- 1 for _ in range (len (graph))]
23
+ res = []
24
+
25
+ def dfs (i ):
26
+ # 暂时定位为不安全节点,等到循环结束改为安全节点
27
+ visited[i] = 0
28
+ for j in graph[i]:
29
+ # 如果找到已经访问过的不安全节点,说明有环,直接返回
30
+ if visited[j] == 0 or (visited[j] == - 1 and dfs(j)):
31
+ return True
32
+ # 已经访问并且确认为安全节点
33
+ visited[i] = 1
34
+ res.append(i)
35
+ return False
36
+
37
+ for i in range (len (graph)):
38
+ if visited[i] == - 1 :
39
+ dfs(i)
40
+ return sorted (res)
41
+ ```
You can’t perform that action at this time.
0 commit comments