- 207. 课程表 : boolean">207. 课程表 : boolean
- 210. 课程表 II | number[]">210. 课程表 II | number[]
207. 课程表 : boolean
BFS
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
let edges: number[][] = 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 visited: number = 0;
while (queue.length) {
visited += 1;
const u = queue.shift();
for (let v of edges[u]) {
indeg[v] -= 1;
if (!indeg[v]) {
queue.push(v);
}
}
}
return visited == numCourses;
};
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 : [];
};