Find Eventual Safe States
LeetCode 802 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Three-colour DFS; safe = finished without touching the path.
मी Find Eventual Safe States (LeetCode 802) असा सोडवला — Topological Sort / DAG पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
A node is unsafe if some path from it reaches a cycle. Run DFS with three states: unvisited, on the current path, and proven safe. A node is safe only if every neighbour is safe.
Approach
- 1
state 0 unvisited, 1 on path, 2 safe.
- 2
DFS: hitting a state-1 node means a cycle → unsafe.
- 3
If all neighbours are safe, mark state 2.
- 4
Collect state-2 nodes in order.
मी कसा सोडवला
DFS with statesPythonO(V+E) time
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
#if a node is part of a cycle, it can't be safe node
n = len(graph)
visited = [0]*n #0- unvisited, 1 - path visited, 2 - can path visit but safe
def dfs(node):
visited[node]=1
for adj_node in graph[node]:
if visited[adj_node]==0:
if dfs(adj_node):
return True
elif visited[adj_node]==1:
return True
visited[node]=2
return False
for node in range(n):
if visited[node]==0:
dfs(node)
res =[]
for node in range(n):
if visited[node]==2:
res.append(node)
return res
Find Eventual Safe States — वारंवार विचारले जाणारे प्रश्न
Find Eventual Safe States मागील intuition काय आहे?
A node is unsafe if some path from it reaches a cycle. Run DFS with three states: unvisited, on the current path, and proven safe. A node is safe only if every neighbour is safe.
Find Eventual Safe States (LeetCode 802) कसा सोडवावा?
1. state 0 unvisited, 1 on path, 2 safe. 2. DFS: hitting a state-1 node means a cycle → unsafe. 3. If all neighbours are safe, mark state 2. 4. Collect state-2 nodes in order.
Find Eventual Safe States ची time आणि space complexity किती आहे?
Time: O(V + E). Space: O(V). (Accepted approach: DFS with states.)
Find Eventual Safe States मध्ये सामान्य चुका कोणत्या?
Leave unsafe nodes at state 1 — that's what marks them.