Find Eventual Safe States
Example:
Input:
graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output:
[2,4,5,6]
Here is a diagram of the above graph.
Last updated
Example:
Input:
graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output:
[2,4,5,6]
Here is a diagram of the above graph.
Last updated
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n = len(graph)
rg = collections.defaultdict(list)
for i in range(n):
for j in graph[i]:
rg[j].append(i)
out = [len(graph[i]) for i in range(n)]
q = [i for i in range(n) if out[i] == 0]
res = []
while q:
cur = q.pop()
res.append(cur)
for x in rg[cur]:
out[x] -= 1
if out[x] == 0:
q.append(x)
return sorted(res)The idea is to just use plain DFS with a state = {Initial=0, InProgress=1, Completed=2 }.
When traversing through the graph, if we detect a cycle by encountering a node which is InProgress
if visited[node] == 1
OR
by visiting a node that is already part of a cycle
node in cycleclass Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n = len(graph)
v = [0]*n
def dfs(i):
if not v[i]:
v[i] = 2
v[i] = 1
for j in graph[i]:
if v[j] == 1 or v[j] == 0 and not dfs(j):
return False
v[i] = 2
return True
return list(filter(dfs,range(n))) #注意filter用法