swift 文章收集iOS学习记录今日看点

Swift最短路径之Dijkstra(单源最短路)算法

2016-08-02  本文已影响301人  我系哆啦

Dijkstra“单源最短路”,是指指定一个点(源点)到其余各个顶点的最短路径。例如:求下图中的1号顶点到其他顶点的最短路径。


dijkstra.png

<pre>
let max:Int = 10000
var map = [[0, 1, 12, max, max, max],
[max, 0, 9, 3, max, max],
[max, max, 0, max, 5, max],
[max, max, 4, 0, 13, 15],
[max, max, max, max, 0, 4],
[max, max, max, max, max, 0]]

func dijkstra(map:[Array<Int>]) -> [Int] {

var book = Array.init(repeatElement(0, count: map.count))
var dist = map.first!

book[0] = 1
for i in 0..<(map.count - 1) {
    
    //取出离源点最近的点
    var min = max
    var u = 0
    
    for j in 0..<map.count {
        if (book[j] == 0) && (map[i][j] < min)  {
            min = map[i][j]
            u = j
        }
    }
    book[u] = 1
                                                                                                                                                                                                                                                                              
    //松弛所有边
    for v in 0..<map.count {
        if map[u][v] < max {
            if dist[v] > (dist[u] + map[u][v]) {
                dist[v] = dist[u] + map[u][v]
            }
        }
    }
}

return dist

}
print(dijkstra(map: map)) //[0, 1, 8, 4, 13, 17]
</pre>

上一篇下一篇

猜你喜欢

热点阅读