207. 课程表 : boolean

BFS

  1. function canFinish(numCourses: number, prerequisites: number[][]): boolean {
  2. let edges: number[][] = Array.from({ length: numCourses }, () => ([]));
  3. let indeg = new Array(numCourses).fill(0);
  4. for (let [b, a] of prerequisites) {
  5. edges[a].push(b);
  6. indeg[b] += 1;
  7. }
  8. let queue = [];
  9. for (let i = 0; i < numCourses; i++) {
  10. if (!indeg[i]) {
  11. queue.push(i);
  12. }
  13. }
  14. let visited: number = 0;
  15. while (queue.length) {
  16. visited += 1;
  17. const u = queue.shift();
  18. for (let v of edges[u]) {
  19. indeg[v] -= 1;
  20. if (!indeg[v]) {
  21. queue.push(v);
  22. }
  23. }
  24. }
  25. return visited == numCourses;
  26. };

DFS 【逆向思维】

function canFinish(numCourses: number, prerequisites: number[][]): boolean {
    let edges: number[][] = Array.from({length: numCourses}, () => ([]));
    let visited = new Array(numCourses).fill(0);
    // 0 未搜索, 1 搜索中, 2 已完成
    let valid = true;

    for (let [b, a] of prerequisites) {
        edges[a].push(b);
    }

    // console.log(edges)
    function dfs (u: number): void {
        visited[u] = 1;
        for (let v of edges[u]) {
            let curVisited = visited[v];
            if (!curVisited) {
                dfs(v);
                if (!valid) return;
            } else if (curVisited == 1) {
                valid = false;
                return;
            }
        }
        visited[u] = 2;
    }

    for (let i = 0; i < numCourses; i++) {
        if (valid && !visited[i]) {
            dfs(i);
        }
    }

    return valid;
};

210. 课程表 II | number[]

function findOrder(numCourses: number, prerequisites: number[][]): number[] {
    let edges = Array.from({ length: numCourses }, ()  => ([]));
    let indeg = new Array(numCourses).fill(0);
    for (let [b, a] of prerequisites) {
        edges[a].push(b);
        indeg[b] += 1;
    }

    let queue = [];
    for (let i = 0; i < numCourses; i++) {
        if (!indeg[i]) {
            queue.push(i);
        }
    }

    let ans = [];
    while (queue.length) {
        const u = queue.shift();
        ans.push(u);
        for (let v of edges[u]) {
            indeg[v] -= 1;
            if (!indeg[v]) {
                queue.push(v);
            }
        }
    }
    return ans.length == numCourses ? ans : [];
};