最短路徑
用於計算一個節點到其他所有節點的最短路徑。主要特點是以起始點爲中心向外層層擴展,直到擴展到終點爲止。廣度優先遍歷算法能得出最短路徑的最優解,但由於它遍歷計算的節點很多,所以效率低。
scala 實現
下面的代碼:
1 創建一個隊列,遍歷的起始點放入隊列,新建一個 boolean 數組、新建距離數組,父親頂點數組
2 從隊列中取出一個元素,收集它,將其標記爲已訪問,將父親頂點和距離存到數組中,並將其未訪問過的子結點放到隊列中
3 重複2,直至隊列空
4.遍歷完後,通過查詢距離數組,父親頂點數組,一步步找到source頂點,得到最短路徑和最短距離
import com.datastructure.Graph
import scala.collection.mutable.{ArrayBuffer, Queue}
class USSSPath {
private var G: Graph = _
private var source: Int = _
private var visited: Array[Boolean] = _
private var pre: Array[Int] = _
private var dis: Array[Int] = _
def this(g: Graph, s: Int) {
this()
G = g
source = s
visited = Array.ofDim[Boolean](g.getV())
pre = Array.ofDim[Int](g.getV())
dis = Array.ofDim[Int](g.getV())
for (i <- 0 until g.getV()) {
pre(i) = -1
dis(i) = -1
}
bfs(s)
dis.foreach(println)
}
def bfs(s: Int): Unit = {
val queue = Queue[Int]()
queue.enqueue(s)
visited(s) = true
pre(s) = s
dis(s) = 0
while (!queue.isEmpty) {
val v = queue.dequeue()
for (w <- G.getAdjacentSide(v)) {
if (!visited(w)) {
queue.enqueue(w)
visited(w) = true
pre(w) = v
dis(w) = dis(v) + 1
}
}
}
}
def isConnectedTo(t: Int): Boolean = {
visited(t)
}
def path(t: Int): Iterator[Int] = {
var res = ArrayBuffer[Int]()
if (!isConnectedTo(t)) {
res.iterator
}
var cur = t
while (cur != source) {
res += cur
cur = pre(cur)
}
res += source
res = res.reverse
res.iterator
}
def distance(t:Int): Int ={
dis(t)
}
}
object USSSPath {
def apply(g: Graph, s: Int): USSSPath = new USSSPath(g, s)
def main(args: Array[String]): Unit = {
val g = Graph("./data/graph/g.txt")
val ussspath = USSSPath(g, 0)
println()
ussspath.path(6).foreach(x => print(x + " => "))
println()
println(ussspath.distance(6))
}
}
// 0 => 2 => 6 =>
// 2
g.txt
7 7
0 1
0 2
1 3
1 4
2 3
2 6
5 6