數據結構 -- 圖中兩點間的路徑

無向圖中的路徑

路徑:在圖中,兩點間邊構成的序列,比如圖中0到6中一條路徑0 -> 1 -> 3 -> 2 -> 6。一般圖中兩點之間的路徑不止一條。這裏的路徑只要找到一條就返回。
在這裏插入圖片描述


scala 實現

import scala.collection.mutable.ArrayBuffer

class Path {
  private var G: Graph = _
  private var source: Int = _
  private var target: Int = _
  private var pre: Array[Int] = _
  private var visited: Array[Boolean] = _

  def this(g: Graph, s: Int, t: Int) {
    this()
    G = g
    source = s
    target = t
    visited = Array.ofDim[Boolean](g.getV())
    pre = Array.ofDim[Int](g.getV())
    for (i <- 0 until pre.length) {
      pre(i) = -1
    }
    dfs(s, s)
    //visited.foreach(println)
  }

  def dfs(v: Int, parent: Int): Boolean = {
    visited(v) = true
    pre(v) = parent
    if (v == target) {
      true
    }

    for (elem <- G.getAdjacentSide(v)) {
      if (!visited(elem)) {
        if (dfs(elem, v)) {
          true
        }
      }
    }
    false
  }

  def isConnected(): Boolean = {
    visited(target)
  }

  def path(): Iterator[Int] = {
    val res = ArrayBuffer[Int]()
    if (!isConnected()) {
      res.toIterator
    } else {
      var cur = target
      while (cur != source) {
        res += cur
        cur = pre(cur)
      }
      res += source
      res.reverse.toIterator
    }
  }
}

object Path {
  def apply(g: Graph, s: Int, t: Int): Path = new Path(g, s, t)

  def main(args: Array[String]): Unit = {
    val graph = Graph().createGraph("./data/graph/g.txt")
    Path(graph, 0, 6).path().foreach(x => print(x + " => "))
    println
    println("-----------------------------------------------")
    Path(graph, 0, 5).path().foreach(x => print(x + " => "))
    println
    println("-----------------------------------------------")
    println
    Path(graph, 0, 1).path().foreach(x => print(x + " => "))
  }
}

//0 => 1 => 3 => 2 => 6 => 
//-----------------------------------------------
//
//-----------------------------------------------
//
//0 => 1 => 

g.txt

7 6
0 1
0 2
1 3
1 4
2 3
2 6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章