广度优先搜索:最短距离(BFS)

时间:2015-12-17 04:19:18

标签: ios swift algorithm data-structures

https://www.hackerrank.com/challenges/bfsshortreach

我的策略是使用整数和无序集保留Node及其相应的相邻节点的数组。 然后我从起始节点开始并在整个过程中进行迭代,保留一组所有相应的相邻节点,并在我访问我已经访问的任何节点时终止。

感谢任何愿意帮助我的Swifters!花了一天时间试图解决这个问题,这让我发疯了。 :(

let testCases : Int = Int(readLine()!)!
for i in 0..<testCases
{
    let inputArray : [Int] = String(readLine()!).characters.split(" ").map{Int(String($0))!}
    let numberOfNodes : Int = inputArray[0]
    let numberOfEdges : Int = inputArray[1]
    var dictionary : [Int : Set<Int>] = [:]
    var countDictionary : [Int : Int] = [:]

    for j in 0..<numberOfEdges
    {
        let edge : [Int] = String(readLine()!).characters.split(" ").map{Int(String($0))!}
        let start : Int = edge[0]
        let end : Int = edge[1]

        if let val = dictionary[start]
        {
            dictionary[start]!.insert(end)
        }
        else
        {
            dictionary[start] = Set.init(arrayLiteral: end)
        }

        if let val = dictionary[end]
        {
            dictionary[end]!.insert(start)
        }

        else
        {
            dictionary[end] = Set.init(arrayLiteral: start)
        }
    }

    let temp : [Int] = String(readLine()!).characters.split(" ").map{Int(String($0))!}
    let startPoint : Int = temp[0]

    var traversed : Set<Int> = Set()

    func iterate(node : Int, _ count : Int)
    {
        let newCount = count + 6
        var temp : [Int] = []

        if let val = dictionary[node]
        {
            for i in val
            {
                temp.append(i)
            }
        }
        if let val = countDictionary[node]
        {
            if count < val
            {
                countDictionary[node]! = count
            }
        }
        else
        {
            countDictionary[node] = count
        }

        if traversed.contains(node)
        {
            return
        }

        traversed.insert(node)

        for j in temp
        {
            iterate(j, newCount)
        }
    }
    iterate(startPoint, 0)

    for z in 0..<numberOfNodes
    {
        if let val = countDictionary[z + 1]
        {
            if val > 0
            {
                print(val, terminator: " ")
            }
        }
        else
        {
            print(-1, terminator: " ")
        }
    }
    print(" ")
}

0 个答案:

没有答案