Skip to content

Commit

Permalink
Graph (soapyigu#373)
Browse files Browse the repository at this point in the history
* Refactor code style for course schedule I & II

* Delete redundant solutions

* Refactor code style
  • Loading branch information
soapyigu authored Jan 13, 2023
1 parent bcbd9ce commit e9253b8
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 165 deletions.
66 changes: 0 additions & 66 deletions DFS/CourseSchedule.swift

This file was deleted.

64 changes: 0 additions & 64 deletions DFS/CourseScheduleII.swift

This file was deleted.

14 changes: 5 additions & 9 deletions Graph/CourseSchedule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,21 @@
toCourses[courses[1], default:[]].append(courses[0])
}

var queue = (0..<numCourses).filter { inDegrees[$0] == 0 }, validCourseCount = 0
var queue = (0..<numCourses).filter { inDegrees[$0] == 0 }, validCoursesCount = 0

while !queue.isEmpty {
let course = queue.removeFirst()

validCourseCount += 1
validCoursesCount += 1

guard let toCourses = toCourses[course] else {
continue
}

for toCourse in toCourses {
for toCourse in toCourses[course] ?? [] {
inDegrees[toCourse] -= 1
if inDegrees[toCourse] == 0 {
queue.append(toCourse)
}
}
}

return validCourseCount == numCourses
return validCoursesCount == numCourses
}
}
}
46 changes: 20 additions & 26 deletions Graph/CourseScheduleII.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,30 @@
*
*/

class CourseScheduleII {
class CourseScheduleII {
func findOrder(_ numCourses: Int, _ prerequisites: [[Int]]) -> [Int] {
var inDegrees = Array(repeating: 0, count: numCourses), fromTo = [Int: [Int]]()
var coursesCouldTake = [Int]()

// init graph
for prerequisite in prerequisites {
fromTo[prerequisite[1], default: []].append(prerequisite[0])
inDegrees[prerequisite[0]] += 1
var indegrees = Array(repeating: 0, count: numCourses), toCourses = [Int: [Int]]()

for pres in prerequisites {
indegrees[pres[0]] += 1
toCourses[pres[1], default: []].append(pres[0])
}
var queue = (0..<numCourses).filter { inDegrees[$0] == 0 }

var queue = (0..<numCourses).filter { indegrees[$0] == 0 }, result = [Int]()

while !queue.isEmpty {
let currentCourse = queue.removeFirst()
coursesCouldTake.append(currentCourse)

guard let toCourses = fromTo[currentCourse] else {
continue
}

toCourses.forEach {
inDegrees[$0] -= 1

if inDegrees[$0] == 0 {
queue.append($0)
let course = queue.removeFirst()

result.append(course)

for toCourse in toCourses[course] ?? [] {
indegrees[toCourse] -= 1
if indegrees[toCourse] == 0 {
queue.append(toCourse)
}
}
}
return coursesCouldTake.count == numCourses ? coursesCouldTake : [Int]()

return result.count == numCourses ? result : [Int]()
}
}
}

0 comments on commit e9253b8

Please sign in to comment.