Skip to content

Commit

Permalink
Fix BFSWithDepth not stopping at the correct depth
Browse files Browse the repository at this point in the history
This commit fixes BFSWithDepth such that it stops after visiting all
nodes at the depth the visit callback first returned false.

Note: This also affects BFS as it invokes the BFSWithDepth
function.
  • Loading branch information
s111 committed Sep 21, 2023
1 parent b3f630d commit f0383fb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
7 changes: 4 additions & 3 deletions traversal.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ func BFSWithDepth[K comparable, T any](g Graph[K, T], start K, visit func(K, int
queue = append(queue, start)
depth := 0

for len(queue) > 0 {
var stop bool
for len(queue) > 0 && !stop {
depth++

for verticesAtDepth := len(queue); verticesAtDepth > 0; verticesAtDepth-- {
Expand All @@ -140,8 +141,8 @@ func BFSWithDepth[K comparable, T any](g Graph[K, T], start K, visit func(K, int
queue = queue[1:]

// Stop traversing the graph if the visit function returns true.
if stop := visit(currentHash, depth); stop {
break
if stop = visit(currentHash, depth) || stop; stop {
continue
}

for adjacency := range adjacencyMap[currentHash] {
Expand Down
13 changes: 6 additions & 7 deletions traversal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ func TestDirectedBFSWithDepth(t *testing.T) {
edges []Edge[int]
startHash int
expectedVisits map[int]int
stopAtVertex int
stopAtDepth int
}{
"traverse entire graph with 3 vertices": {
vertices: []int{1, 2, 3},
Expand All @@ -341,7 +341,7 @@ func TestDirectedBFSWithDepth(t *testing.T) {
2: 2,
3: 2,
},
stopAtVertex: -1,
stopAtDepth: -1,
},
"traverse graph with 6 vertices until vertex 4": {
vertices: []int{1, 2, 3, 4, 5, 6},
Expand All @@ -357,9 +357,8 @@ func TestDirectedBFSWithDepth(t *testing.T) {
1: 1,
2: 2,
3: 2,
4: 3,
},
stopAtVertex: 4,
stopAtDepth: 2,
},
"traverse a disconnected graph": {
vertices: []int{1, 2, 3, 4},
Expand All @@ -372,7 +371,7 @@ func TestDirectedBFSWithDepth(t *testing.T) {
1: 1,
2: 2,
},
stopAtVertex: -1,
stopAtDepth: -1,
},
}

Expand All @@ -394,8 +393,8 @@ func TestDirectedBFSWithDepth(t *testing.T) {
visit := func(value, depth int) bool {
visited[value] = depth

if test.stopAtVertex != -1 {
if value == test.stopAtVertex {
if test.stopAtDepth != -1 {
if value == test.stopAtDepth {
return true
}
}
Expand Down

0 comments on commit f0383fb

Please sign in to comment.