Skip to content

Commit b561094

Browse files
committed
Adding node consumer support on graph BFS
1 parent 0b42d46 commit b561094

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

data_structures/graphs/bfs.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,13 @@ def initialize(visited, parents, distances)
2525
##
2626
# Performs a breadth-first search for the provided graph, starting at the given node.
2727
# Returns the search result (see GraphBfsResult).
28+
# Nodes are consumed upon discovery using the provided node consumer (nothing, by default).
2829
#
2930
# The algorithm has a time complexity of O(|V| + |E|), where:
3031
# - |V| is the number of nodes in the graph;
3132
# - |E| is the number of edges in the graph.
3233

33-
def bfs(graph, start_node)
34+
def bfs(graph, start_node, node_consumer=method(:do_nothing_on_node))
3435
seen = Set[]
3536
visited = Set[]
3637
parents = { start_node => nil }
@@ -41,6 +42,7 @@ def bfs(graph, start_node)
4142
q.push(start_node)
4243
until q.empty?
4344
node = q.pop
45+
node_consumer.call(node)
4446
for neighbor in graph.neighbors(node)
4547
unless seen.include?(neighbor)
4648
seen.add(neighbor)
@@ -54,3 +56,7 @@ def bfs(graph, start_node)
5456

5557
GraphBfsResult.new(visited, parents, distances)
5658
end
59+
60+
private
61+
def do_nothing_on_node(node)
62+
end

data_structures/graphs/bfs_test.rb

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def test_bfs_visits_single_graph_node
1818
}
1919
end
2020

21-
def test_bfs_visits_undirected_graph_fully
21+
def test_bfs_visits_graph_fully
2222
graph = UnweightedGraph.new(nodes: [:u, :v, :w, :x], directed: false)
2323
graph.add_edge(:u, :v)
2424
graph.add_edge(:u, :w)
@@ -41,7 +41,7 @@ def test_bfs_visits_undirected_graph_fully
4141
}
4242
end
4343

44-
def test_bfs_visits_undirected_graph_partially
44+
def test_bfs_visits_graph_partially
4545
graph = UnweightedGraph.new(nodes: [:u, :v, :w, :x, :y, :z], directed: false)
4646
graph.add_edge(:u, :v)
4747
graph.add_edge(:w, :x)
@@ -64,4 +64,15 @@ def test_bfs_visits_undirected_graph_partially
6464
:z => 2
6565
}
6666
end
67+
68+
def test_bfs_visits_with_node_consumer
69+
graph = UnweightedGraph.new(nodes: [:u, :v, :w], directed: false)
70+
graph.add_edge(:u, :v)
71+
graph.add_edge(:u, :w)
72+
73+
visit_order = []
74+
bfs(graph, :w, ->(node) { visit_order.append(node) })
75+
76+
assert visit_order == [:w, :u, :v]
77+
end
6778
end

0 commit comments

Comments
 (0)