Leecode:Course Schedule(JS解答)
思路:采用拓扑原理,依据题意构成有向无环图,判断是否存在环路
在解题时,使用邻接表来存储边,同时用一个数组存储每个节点的入度(即有多少有向边指向它),让后广度优先遍历去除入度为0的节点,如果最后能顺利去除所有节点,则证明构成有向无环图。
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
let adjacencyList:number[][] = [];
let indegrees:number[] = new Array(numCourses).fill(0); //入度表
let tempArr:number[] = []; //放置所有入度为0的节点
for(let i = 0; i < numCourses; i++){
adjacencyList.push(new Array());
}
for(let val of prerequisites){
indegrees[val[0]] ++; //统计每个节点的入度
adjacencyList[val[1]].push(val[0]); //构建邻接表
}
for(let i = 0; i < numCourses; i++){
if(indegrees[i] == 0) tempArr.push(i); //放置所有入度为0的节点
}
while (tempArr.length > 0){
let firstNode:number = tempArr.shift() as number; //弹出首个入度为0的节点,进行bfs
numCourses--;
for(let val of adjacencyList[firstNode]){ //弹出当前入度为0的节点后,与它相邻的所有节点进行更新
indegrees[val]--;
if(indegrees[val] == 0) tempArr.push(val);
}
}
return numCourses == 0;
};
朋友最近问我,你有没有想过换行啊?说实话,我早就想换行了,我代码风格很不好…
Leecode:Course Schedule II(一起吧)
function findOrder(numCourses: number, prerequisites: number[][]): number[] {
let adjacencyList:number[][] = [];
let indegrees:number[] = new Array(numCourses).fill(0);
let tempArr:number[] = [];
let res:number[] = [];
for(var i = 0; i < numCourses; i++){
adjacencyList.push(new Array());
}
for(let val of prerequisites){
adjacencyList[val[1]].push(val[0]);
indegrees[val[0]]++;
}
for(let i = 0; i < numCourses; i++){
if(indegrees[i] == 0) tempArr.push(i);
}
while (tempArr.length > 0){
let firstNode:number = tempArr.shift() as number;
numCourses--;
res.push(firstNode);
for(let val of adjacencyList[firstNode]){
indegrees[val]--;
if(indegrees[val] == 0) tempArr.push(val);
}
}
return numCourses == 0?res:[];
};