# Find Eventual Safe States (Leetcode 802)

Problem Link: <https://leetcode.com/problems/find-eventual-safe-states/>

```python
from collections import defaultdict
class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        
        m=len(graph)
        
        adj=defaultdict(list)
        # Get the adjacency list in reverse order
        for i in range(m):
            for j in graph[i]:
                adj[j].append(i)
            
        
        # Calculate the indegree
        indegree=[0 for i in range(m)]
        for i in adj:
            for j in adj[i]:
                indegree[j]+=1
        
        # Put the vertices with 0 indegree into q
        q=[]
        for i in range(m):
            if(indegree[i]==0):
                q.insert(0,i)
        
        # Perform BFS
        ans=[]
        while(len(q)>0):
            for _ in range(len(q)):
                curr=q.pop()
                ans.append(curr)
                for i in adj[curr]:
                    indegree[i]-=1
                    if(indegree[i]==0):
                        q.insert(0,i)
        return sorted(ans)
```
