ruby 广度优先搜索w / Ruby

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 广度优先搜索w / Ruby相关的知识,希望对你有一定的参考价值。

require 'awesome_print'
require 'matrix'
require 'thread'

# Undirected Graph
# A = Matrix[
#   [0, 1, 0, 0, 1],
#   [1, 0, 1, 1, 1],
#   [0, 1, 0, 1, 0],
#   [0, 1, 1, 0, 1],
#   [1, 1, 0, 1, 0]
# ]

# Directed Graph
A = Matrix[
  [0, 1, 0, 1, 0, 0],
  [0, 0, 0, 0, 1, 0],
  [0, 0, 0, 0, 1, 1],
  [0, 1, 0, 0, 0, 0],
  [0, 0, 0, 1, 0, 0],
  [0, 0, 0, 0, 0, 1]
]

class Vertex
  attr_accessor :adjacent_vertices, :color, :distance, :title, :predecessor

  def initialize
    @adjacent_vertices =              []
    @color             =          'WHITE'
    @distance          = Float::INFINITY
    @predecessor       =             nil
  end
end

# Build the vertices
g = []
A.row_count.times do |i|
  v = Vertex.new
  v.title = i;
  g << v
end

# Get the all adjacent vertices
g.each do |vertex|
  A.column_count.times do |column|
    if A[vertex.title, column] == 1
      vertex.adjacent_vertices << column
    end
  end
end

# s
s = 0
g[s].color    = 'GRAY'
g[s].distance =      0

puts "###########################"
puts "## Breadth First Search! ##"
puts "###########################"

ap 'Before:'
ap g

queue = Queue.new
queue.push(g[s].title)

while !queue.empty?
  u = queue.pop

  g[u].adjacent_vertices.each do |v|
    if g[v].color == 'WHITE'
      g[v].color       =            'GRAY'
      g[v].distance    = g[u].distance + 1
      g[v].predecessor =                 u
      queue.push(g[v].title)
    end
  end

  g[u].color = 'BLACK'
end

ap 'After:'
ap g

以上是关于ruby 广度优先搜索w / Ruby的主要内容,如果未能解决你的问题,请参考以下文章

ruby 深度优先使用Ruby进行搜索

搜索-广度优先搜索(BFS)

ruby 深度优先搜索

图的遍历之深度优先和广度优先

算法_图的深度优先搜索和广度优先搜索

什么是图的深度优先遍历?什么是图的广度优先遍历?