mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-11-16 19:50:00 +01:00
Adding node consumer support on graph BFS
This commit is contained in:
parent
0b42d46b83
commit
b561094aa5
2 changed files with 20 additions and 3 deletions
|
@ -25,12 +25,13 @@ end
|
|||
##
|
||||
# Performs a breadth-first search for the provided graph, starting at the given node.
|
||||
# Returns the search result (see GraphBfsResult).
|
||||
# Nodes are consumed upon discovery using the provided node consumer (nothing, by default).
|
||||
#
|
||||
# The algorithm has a time complexity of O(|V| + |E|), where:
|
||||
# - |V| is the number of nodes in the graph;
|
||||
# - |E| is the number of edges in the graph.
|
||||
|
||||
def bfs(graph, start_node)
|
||||
def bfs(graph, start_node, node_consumer=method(:do_nothing_on_node))
|
||||
seen = Set[]
|
||||
visited = Set[]
|
||||
parents = { start_node => nil }
|
||||
|
@ -41,6 +42,7 @@ def bfs(graph, start_node)
|
|||
q.push(start_node)
|
||||
until q.empty?
|
||||
node = q.pop
|
||||
node_consumer.call(node)
|
||||
for neighbor in graph.neighbors(node)
|
||||
unless seen.include?(neighbor)
|
||||
seen.add(neighbor)
|
||||
|
@ -54,3 +56,7 @@ def bfs(graph, start_node)
|
|||
|
||||
GraphBfsResult.new(visited, parents, distances)
|
||||
end
|
||||
|
||||
private
|
||||
def do_nothing_on_node(node)
|
||||
end
|
||||
|
|
|
@ -18,7 +18,7 @@ class TestBfs < Minitest::Test
|
|||
}
|
||||
end
|
||||
|
||||
def test_bfs_visits_undirected_graph_fully
|
||||
def test_bfs_visits_graph_fully
|
||||
graph = UnweightedGraph.new(nodes: [:u, :v, :w, :x], directed: false)
|
||||
graph.add_edge(:u, :v)
|
||||
graph.add_edge(:u, :w)
|
||||
|
@ -41,7 +41,7 @@ class TestBfs < Minitest::Test
|
|||
}
|
||||
end
|
||||
|
||||
def test_bfs_visits_undirected_graph_partially
|
||||
def test_bfs_visits_graph_partially
|
||||
graph = UnweightedGraph.new(nodes: [:u, :v, :w, :x, :y, :z], directed: false)
|
||||
graph.add_edge(:u, :v)
|
||||
graph.add_edge(:w, :x)
|
||||
|
@ -64,4 +64,15 @@ class TestBfs < Minitest::Test
|
|||
:z => 2
|
||||
}
|
||||
end
|
||||
|
||||
def test_bfs_visits_with_node_consumer
|
||||
graph = UnweightedGraph.new(nodes: [:u, :v, :w], directed: false)
|
||||
graph.add_edge(:u, :v)
|
||||
graph.add_edge(:u, :w)
|
||||
|
||||
visit_order = []
|
||||
bfs(graph, :w, ->(node) { visit_order.append(node) })
|
||||
|
||||
assert visit_order == [:w, :u, :v]
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue