There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
//
Graph 위상정렬(Topology sort) 문제이다.
각 Node의 차수(indegree)를 que를 통해 계산해 답을 구하는 방법과, DFS로 구하는 방법 2가지 해결법이 있다.
DFS를 공부중이기 때문에 DFS로 풀어보았다.
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {number[]}
*/
var findOrder = function(numCourses, prerequisites) {
let obj = new Object();
const visiting = new Set();
const visited = new Set();
let stack = [];
let isCycle = false;
prerequisites.map(arr => {
const [course, pre] = arr
obj[course] = [...(obj[course] ?? []), pre]
})
// console.log(obj)
const DFS = function (v) {
visiting.add(v)
let edges = obj[v];
if(edges) {
for(let e of edges){
if(visiting.has(e)){
isCycle = true;
return;
}
if(visited.has(e)){
continue;
}
DFS(e)
}
}
visiting.delete(v)
visited.add(v)
// console.log(visiting, visited, stack)
stack.push(v)
}
// console.log(visited)
// console.log(stack)
for(let i =0; i<numCourses; i++){
if(!visited.has(i)) DFS(i)
}
return isCycle ? [] : stack
};
visited,와 visiting을 변수 하나로 합칠수 있음.