Skip to content

Commit aeaa1dc

Browse files
authored
Update 207-course-schedule.js
1 parent 095273b commit aeaa1dc

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

207-course-schedule.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,40 @@ const canFinish = function(vertices, edges) {
7272
}
7373
return sortedOrder.length === vertices ? true : false
7474
}
75+
76+
// another
77+
78+
/**
79+
* @param {number} numCourses
80+
* @param {number[][]} prerequisites
81+
* @return {boolean}
82+
*/
83+
const canFinish = function(numCourses, prerequisites) {
84+
const set = new Set(), hash = {}
85+
for(let i = 0; i < prerequisites.length; i++) {
86+
const [cur, pre] = prerequisites[i]
87+
if(hash[cur] == null) hash[cur] = new Set()
88+
hash[cur].add(pre)
89+
}
90+
const q = []
91+
92+
for(let i = 0; i < numCourses; i++) {
93+
if(hash[i] == null) q.push(i)
94+
}
95+
let visited = 0
96+
97+
while(q.length) {
98+
const cur = q.shift()
99+
visited++
100+
Object.keys(hash).forEach(k => {
101+
if(hash[k].has(cur)) {
102+
hash[k].delete(cur)
103+
}
104+
if(hash[k].size === 0) {
105+
delete hash[k]
106+
q.push(+k)
107+
}
108+
})
109+
}
110+
return visited === numCourses
111+
};

0 commit comments

Comments
 (0)