File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Day-11/Find Eventual Safe States Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ # Approach
2+ <br />Remove the nodes having outdegree 0 and add to ans , if no nodes return.
3+ <br />The nodes which are connected to the above nodes will have 1 less outdegree. Repeat for all O outdegree nodes.
4+ <br />Sort the ans and return.
5+ ```
6+ class Solution {
7+ public:
8+ vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
9+ int n=graph.size();
10+ vector<int> outdegree(n,0);
11+ unordered_map<int,vector<int>> m;
12+ for(int i=0;i<n;i++)
13+ {
14+ for(auto it : graph[i])
15+ {
16+ m[it].push_back(i);
17+ }
18+ outdegree[i]=graph[i].size();
19+ }
20+ vector<int> ans;
21+ vector<int> visited(n,0);
22+ while(true)
23+ {
24+ bool flag=0;
25+ for(int i=0;i<n;i++)
26+ {
27+ if(!visited[i] && outdegree[i]==0)
28+ {
29+ ans.push_back(i);
30+ visited[i]=1;
31+ flag=1;
32+ for(auto it : m[i])
33+ outdegree[it]--;
34+ }
35+ }
36+ if(!flag)
37+ break;
38+ }
39+ sort(ans.begin(),ans.end());
40+ return ans;
41+ }
42+ };
43+ ```
You can’t perform that action at this time.
0 commit comments