最短路径
用于计算一个节点到其他所有节点的最短路径。主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止。广度优先遍历算法能得出最短路径的最优解,但由于它遍历计算的节点很多,所以效率低。
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