그래프의 안전한 정점(Safe Nodes) 을 구하는 문제이다. 이를 위해서 위상 정렬을 약간 응용해야하는 문제
주어진 그래프의 방향을 뒤집음 (즉, 역그래프 생성)
for(int i = 0 ; i < graph.size(); i++){
outDegree[i] = graph[i].size();
for(int j = 0 ; j<graph[i].size(); j++){
outEdges[graph[i][j]].push_back(i);
}
}
위상 정렬을 사용하여 안전한 노드 를 판별
class Solution {
public:
vector<int> topologySortedArr;
vector<int> outDegree;
vector<int> outEdges[10001];
void topologySort() {
queue<int> q;
for(int i = 0 ; i<outDegree.size(); i++){
if(outDegree[i] == 0){
q.push(i);
}
}
while(!q.empty()){
int start = q.front();
topologySortedArr.push_back(start);
q.pop();
for(auto next: outEdges[start]){
outDegree[next]--;
if(outDegree[next] == 0){
q.push(next);
}
}
}
}
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
outDegree.resize(graph.size());
for(int i = 0 ; i < graph.size(); i++){
outDegree[i] = graph[i].size();
for(int j = 0 ; j<graph[i].size(); j++){
outEdges[graph[i][j]].push_back(i);
}
}
topologySort();
sort(topologySortedArr.begin(), topologySortedArr.end());
return topologySortedArr;
}
};