문제: https://leetcode.com/problems/course-schedule/
위상정렬로 풀었습니다.
import Foundation
class Solution {
func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
var degrees = Array(repeating: 0, count: numCourses)
var graph = Array(repeating: [Int](), count: numCourses)
var queue = [Int]()
for prerequisite in prerequisites {
degrees[prerequisite[0]] += 1
graph[prerequisite[1]].append(prerequisite[0])
}
for i in 0..<degrees.count {
if degrees[i] == 0 {
queue.append(i)
}
}
while !queue.isEmpty {
let node = queue.removeFirst()
for next in graph[node] {
degrees[next] -= 1
if degrees[next] == 0 {
queue.append(next)
}
}
}
return degrees.reduce(0, +) == 0
}
}
'알고리즘' 카테고리의 다른 글
[Swift] LeetCode - 1038. Binary Search Tree to Greater Sum Tree (0) | 2022.02.17 |
---|---|
[Swift] LeetCode - 297. Serialize and Deserialize Binary Tree (0) | 2022.02.17 |
[Swift] LeetCode - 78. Subsets (0) | 2022.02.16 |
[Swift] LeetCode - 39. Combination Sum (0) | 2022.02.16 |
[Swift] LeetCode - 17. Letter Combinations of a Phone Number (0) | 2022.02.16 |
댓글