@@ -25,33 +25,36 @@ def initialize(visited, parents, distances)
25
25
##
26
26
# Performs a breadth-first search for the provided graph, starting at the given node.
27
27
# Returns the search result (see GraphBfsResult).
28
- # Nodes are consumed upon discovery using the provided node consumer (nothing, by default).
28
+ # Nodes are consumed using the provided consumers upon being first seen, or being completely visited
29
+ # (nothing, by default).
29
30
#
30
31
# The algorithm has a time complexity of O(|V| + |E|), where:
31
32
# - |V| is the number of nodes in the graph;
32
33
# - |E| is the number of edges in the graph.
33
34
34
- def bfs ( graph , start_node , node_consumer = method ( :do_nothing_on_node ) )
35
+ def bfs ( graph , start_node , seen_node_consumer : method ( :do_nothing_on_node ) , visited_node_consumer : method ( :do_nothing_on_node ) )
35
36
seen = Set [ ]
36
37
visited = Set [ ]
37
38
parents = { start_node => nil }
38
39
distances = { start_node => 0 }
39
40
40
41
seen . add ( start_node )
42
+ seen_node_consumer . call ( start_node )
41
43
q = Queue . new
42
44
q . push ( start_node )
43
45
until q . empty?
44
46
node = q . pop
45
- node_consumer . call ( node )
46
47
for neighbor in graph . neighbors ( node )
47
48
unless seen . include? ( neighbor )
48
49
seen . add ( neighbor )
49
50
distances [ neighbor ] = distances [ node ] + 1
50
51
parents [ neighbor ] = node
52
+ seen_node_consumer . call ( neighbor )
51
53
q . push ( neighbor )
52
54
end
53
55
end
54
56
visited . add ( node )
57
+ visited_node_consumer . call ( node )
55
58
end
56
59
57
60
GraphBfsResult . new ( visited , parents , distances )
0 commit comments