Skip to content

Commit b77631d

Browse files
committed
Fix BFSWithDepth not stopping at the correct depth
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.
1 parent b3f630d commit b77631d

File tree

2 files changed

+10
-10
lines changed

2 files changed

+10
-10
lines changed

traversal.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,8 @@ func BFSWithDepth[K comparable, T any](g Graph[K, T], start K, visit func(K, int
131131
queue = append(queue, start)
132132
depth := 0
133133

134-
for len(queue) > 0 {
134+
var stop bool
135+
for len(queue) > 0 && !stop {
135136
depth++
136137

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

142143
// Stop traversing the graph if the visit function returns true.
143-
if stop := visit(currentHash, depth); stop {
144-
break
144+
if stop = visit(currentHash, depth) || stop; stop {
145+
continue
145146
}
146147

147148
for adjacency := range adjacencyMap[currentHash] {

traversal_test.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ func TestDirectedBFSWithDepth(t *testing.T) {
327327
edges []Edge[int]
328328
startHash int
329329
expectedVisits map[int]int
330-
stopAtVertex int
330+
stopAtDepth int
331331
}{
332332
"traverse entire graph with 3 vertices": {
333333
vertices: []int{1, 2, 3},
@@ -341,7 +341,7 @@ func TestDirectedBFSWithDepth(t *testing.T) {
341341
2: 2,
342342
3: 2,
343343
},
344-
stopAtVertex: -1,
344+
stopAtDepth: -1,
345345
},
346346
"traverse graph with 6 vertices until vertex 4": {
347347
vertices: []int{1, 2, 3, 4, 5, 6},
@@ -357,9 +357,8 @@ func TestDirectedBFSWithDepth(t *testing.T) {
357357
1: 1,
358358
2: 2,
359359
3: 2,
360-
4: 3,
361360
},
362-
stopAtVertex: 4,
361+
stopAtDepth: 2,
363362
},
364363
"traverse a disconnected graph": {
365364
vertices: []int{1, 2, 3, 4},
@@ -372,7 +371,7 @@ func TestDirectedBFSWithDepth(t *testing.T) {
372371
1: 1,
373372
2: 2,
374373
},
375-
stopAtVertex: -1,
374+
stopAtDepth: -1,
376375
},
377376
}
378377

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

397-
if test.stopAtVertex != -1 {
398-
if value == test.stopAtVertex {
396+
if test.stopAtDepth != -1 {
397+
if value == test.stopAtDepth {
399398
return true
400399
}
401400
}

0 commit comments

Comments
 (0)