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.