모든 사진 자료에 관한 출처는 아래 알튜비튜 - 튜터링에 있음을 밝힙니다.
https://github.com/Altu-Bitu/Notice
Q. 만약 사이클
이 존재한다면?
...중략
void dfs(int node){
if(visited[node]) //이미 방문한 정점이라면
return;
visited[node]=true; //방문 체크
for(int i=0; i< graph[node].size();i++)
dfs(graph[node][i]);
st.push(node); //더이상 탐색할 정점이 없다면 현재 정점 삽입
//위상정렬
vector<int> topologicalSort(int n, vector<int>& indegree, vector<vector<int>>& graph) {
vector<int> result;
queue<int> q;
for (int i = 1; i <= n; i++) {
if (!indegree[i]) //진입차수가 0이라면
q.push(i); // 큐에 푸시
}
// 큐에 존재하는 정점들을 하나씩 꺼내어 연결을 끊으면서 진입차수가 0인 된 점들을 큐에 푸시함
while (!q.empty()) {
int node = q.front();
q.pop();
result.push_back(node); //현재 정점 순서에 삽입
for (int i = 0; i < graph[node].size(); i++) {
int next_node = graph[node][i]; // node와 연결된 정점들
indegree[next_node]--; //연결된 정점의 진입차수를 1씩 감소
if (!indegree[next_node]) //연결된 정점의 진입차수가 0이 되었다면
q.push(next_node);
}
}
return result;
}