拓扑排序Swift

时间:2019-03-17 11:44:01

标签: swift

我正在尝试使用以下理论在Swift中实现拓扑排序。

https://courses.cs.washington.edu/courses/cse326/03wi/lectures/RaoLect20.pdf

我的代码是:

func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
    guard (prerequisites.count > 0) else {return true}
    var graph : [[Int]] = Array(repeating: [], count: numCourses + 1)
    var inDegree : [Int] = Array(repeating: 0, count: numCourses + 1 )
    for x in prerequisites {
        graph[x[0]] = [x[1]]
        inDegree[x[0]] += 1
    }
    for course in graph.enumerated() {
        print ("To finish course \(course.offset) you must have finished \(course.element)")
    }

    for course in (inDegree.enumerated()) {
        print ("Course \(course.offset) needs \(course.element) courses to be complete")
    }

    var outputArr = [Int]()

    while let currentVertexIndx = (inDegree.enumerated().first { $0.element == 0 }?.offset) {
        outputArr.append( currentVertexIndx )
        for course in graph.enumerated() {

            if (course.element.contains(currentVertexIndx)) {
                inDegree[ course.offset ] -= 1
            }
        }

        inDegree[currentVertexIndx] = -1
    }
    return outputArr.count >= numCourses
}

答案正确的测试:

//canFinish(1, [[1,0]]) // true - to take course 1 you should have finished course 0
//canFinish(2, [[1,0],[0,1]]) // false - to take course 1 you have to have finished course 0, to take 0 you have to have finished course 1
//canFinish(1, []) // true
//canFinish(3, [[1,0],[2,0]]) // true
//canFinish(3, [[2,0],[2,1]]) // true

测试答案不正确

canFinish(10, [[5,6],[0,2],[1,7],[5,9],[1,8],[3,4],[0,6],[0,7],[0,3],[8,9]]) // true, but returns false

问题:使用来自Washington.edu的理论,我的代码不适用于以上输入。怎么了?

1 个答案:

答案 0 :(得分:1)

您应正确填写<key>FacebookAppID</key> <string>XXXXXXX</string> <key>FacebookDisplayName</key> <string>XXXXX</string>

graph

在给定的示例中哪个将产生正确的结果

graph[x[0]] += [x[1]]