数据结构 -- 图的广度优先遍历解决最短路径

最短路径

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


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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值