如何在阵列中查找连接的组件

时间:2018-11-04 14:11:43

标签: arrays ruby algorithm depth-first-search connected-components

我正在尝试使用Hackerrank Roads and Libraries中的算法问题。问题的根源是使用DFS使用数组查找连接的组件(CC)。

这是测试用例:

queries = [
  {
    n_cities_roads: [9,2],
    c_lib_road: [91, 84],
    matrix: [
      [8, 2], [2, 9]
    ]
  },
  {
    n_cities_roads: [5,9],
    c_lib_road: [92, 23],
    matrix: [
      [2,1], [5, 3], [5,1], 
      [3,4], [3,1],  [5, 4], 
      [4,1], [5,2],  [4,2]
    ]
  },
  {
    n_cities_roads: [8,3],
    c_lib_road: [10, 55],
    matrix: [
      [6,4], [3,2], [7,1]
    ]
  },
  {
    n_cities_roads: [1, 0],
    c_lib_road: [5, 3],
    matrix: []
  },

  {
    n_cities_roads: [2, 0],
    c_lib_road: [102, 1],
    matrix: []
  }
]

queries.each do |query|
  (n_city, n_road), (c_lib, c_road) = [*query[:n_cities_roads]], [*query[:c_lib_road]]
  roads_and_libraries n_city, c_lib, c_road, query[:matrix]
end

输出应为:

805
184
80
5
204

我下面的当前解决方案在某些情况下可以获取CC,但并非所有情况都可以。

def dfs(i, visited, matrix)
  visited[i] = true
  unless matrix[i].nil?
    matrix[i].each do |j|
      unless visited[j]
        dfs j, visited, matrix
      end
    end
  end
end

def roads_and_libraries(no_cities, c_lib, c_road, cities)
  return c_lib * no_cities if c_lib <= c_road
  visited, count = Array.new(no_cities, false), 0

  (0..no_cities).each do |i|
    unless visited[i]
      count += 1
      dfs i, visited, cities
    end
  end
  p (c_road * (no_cities - count)) + (c_lib * count)
end

上面带有我的代码的测试输出为:

805
184
7
305

我正在努力了解如何正确使用DFS查找连接的组件。不知道我要去哪里错了。

1 个答案:

答案 0 :(得分:1)

只需打印此行:

p roads_and_libraries n_city, c_lib, c_road, query[:matrix]

不是这个

p (c_road * (no_cities - count)) + (c_lib * count)

因为该方法有返回值:

return c_lib * no_cities if c_lib <= c_road

我不知道算法,但似乎矩阵不能为空[],至少必须为[[1,1]]才能获得所需的输出:

roads_and_libraries 1, 5, 3, [[1,1]] #=> 5
roads_and_libraries 2, 102, 1, [[1,1]] #=> 204

因此,要处理空矩阵,一种方法是将其添加为dfs方法的第一行:

matrix = [[1,1]] if matrix.empty?