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

Posted

tags:

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

require 'awesome_print'
require 'matrix'

# 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, :finish_time, :distance, :title, :predecessor

  def initialize
    @adjacent_vertices =     []
    @color             = 'WHITE'
    @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

puts "#########################"
puts "## Depth First Search! ##"
puts "#########################"

ap 'Before:'
ap g

def dfs_visit(g, u)
  @time       +=     1
  u.distance   =  @time
  u.color      = 'GRAY'

  u.adjacent_vertices.each do |v|
    if g[v].color == 'WHITE'
      g[v].predecessor = u.title
      dfs_visit(g, g[v])
    end
  end

  u.color         = 'BLACK'
  @time          +=       1
  u.finish_time   =   @time
end

def dfs(g)
  g.each do |vertex|
    if vertex.color == 'WHITE'
      dfs_visit(g, vertex)
    end
  end
end

# Actually run the darn thing
@time = 0
dfs(g)

ap 'After:'
ap g

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

ruby 广度优先搜索w / Ruby

ruby Ruby Hash深度搜索没有获得堆栈大小异常

ruby 广度优先搜索

使用多个模块扩展的对象中方法的 Ruby 优先级

ruby 哈希包含另一个哈希,深度检查

在 Ruby 中深度复制对象的最有效方法是啥?