Skip to content

Commit 986df37

Browse files
Day11-q1 sol added #318
1 parent bb473bc commit 986df37

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
```

0 commit comments

Comments
 (0)