gpt4 book ai didi

arrays - 如何在数组中查找连通分量

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:08:35 26 4
gpt4 key购买 nike

我正在尝试 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 来查找连接的组件。不确定我哪里出错了。

最佳答案

只需打印这一行:

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

不是这个

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

因为方法中有return:

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?

关于arrays - 如何在数组中查找连通分量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53141726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com