class

NgLib::BfsGraph

Inherits Reference < Object

$n$ 頂点 $m$ 辺からなるグラフに対して、幅優先探索によって最短経路を求めます。

経路の復元も可能です。

Constructors

new(n : Int)

$n$ 頂点 $0$ 辺からなるグラフを作成します。

graph = BfsGraph.new(n)
Source

Instance methods

add_edge(u : Int, v : Int, directed : Bool = true)

辺 $(u, v)$ を追加します。

directed が true の場合、 有向辺とみなして、$u$ から $v$ への辺のみ生やします。

graph = BfsGraph.new(n)
graph.add_edge(u, v)                 # => (u) <---w---> (v)
graph.add_edge(u, v, directed: true) # => (u) ----w---> (v)
Source
graph
Source
shortest_path(start : Int, dest : Int)

始点 start から終点 dest への最短経路長を返します。

dist = graph.shortest_path(start: 2, dest: 0)
dist # => 12
Source
shortest_path(start : Int)

始点 start から各頂点への最短経路長を返します。

dist = graph.shortest_path(start: 2)
dist # => [3, 8, 0, 7, 1]
Source
shortest_path

全点対間の最短経路長を返します。

dists = graph.shortest_path
dists # => [[0, 1, 3], [1, 0, 2], [1, 1, 0]]
Source
size
Source