Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 802 · Topological Sort / DAG

Find Eventual Safe States

LeetCode 802 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Three-colour DFS; safe = finished without touching the path.

మధ్యస్థంDepth-First SearchBreadth-First SearchGraph TheoryTopological SortKosaraju's Algorithm
LeetCode లో తెరవండి ↗

నేను 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. 1

    state 0 unvisited, 1 on path, 2 safe.

  2. 2

    DFS: hitting a state-1 node means a cycle → unsafe.

  3. 3

    If all neighbours are safe, mark state 2.

  4. 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.