diff --git a/Sources/SwiftGraph/Search.swift b/Sources/SwiftGraph/Search.swift index e4ba9bb..78112ac 100644 --- a/Sources/SwiftGraph/Search.swift +++ b/Sources/SwiftGraph/Search.swift @@ -373,6 +373,7 @@ public extension Graph { var visited: [Bool] = [Bool](repeating: false, count: vertexCount) let queue: Queue = Queue() var pathDict: [Int: Edge] = [Int: Edge]() + visited[fromIndex] = true queue.push(fromIndex) while !queue.isEmpty { let v: Int = queue.pop() @@ -415,6 +416,7 @@ public extension Graph { var visited: [Bool] = [Bool](repeating: false, count: vertexCount) let queue: Queue = Queue() var pathDict: [Int: Edge] = [Int: Edge]() + visited[fromIndex] = true queue.push(fromIndex) while !queue.isEmpty { let v: Int = queue.pop() @@ -460,6 +462,7 @@ public extension Graph { let queue: Queue = Queue() var pathDict: [Int: Edge] = [Int: Edge]() var paths: [[Edge]] = [[Edge]]() + visited[fromIndex] = true queue.push(fromIndex) while !queue.isEmpty { let v: Int = queue.pop() diff --git a/Tests/SwiftGraphTests/SwiftGraphSearchTests.swift b/Tests/SwiftGraphTests/SwiftGraphSearchTests.swift index 91ffd30..c7ad83e 100644 --- a/Tests/SwiftGraphTests/SwiftGraphSearchTests.swift +++ b/Tests/SwiftGraphTests/SwiftGraphSearchTests.swift @@ -477,4 +477,13 @@ class SwiftGraphSearchTests: XCTestCase { XCTAssertTrue(endCities.contains("San Francisco"), "Should contain a route to San Francisco") } } + + func testFindAllBfsDoesNotRevisitStartVertex() { + let g = UnweightedGraph(vertices: ["A", "B", "C"]) + g.addEdge(from: "A", to: "B", directed: false) + g.addEdge(from: "B", to: "C", directed: false) + let result = g.findAllBfs(from: "A") { _ in true } + XCTAssertEqual(result.count, 3, "Each vertex must be reported exactly once") + XCTAssertEqual(result.first?.count, 0, "The path to the start vertex is empty") + } } diff --git a/Tests/SwiftGraphTests/XCTestManifests.swift b/Tests/SwiftGraphTests/XCTestManifests.swift index 71c9ad7..c50f6dd 100644 --- a/Tests/SwiftGraphTests/XCTestManifests.swift +++ b/Tests/SwiftGraphTests/XCTestManifests.swift @@ -106,6 +106,7 @@ extension SwiftGraphSearchTests { ("testDfsVisitOrderWithCycle", testDfsVisitOrderWithCycle), ("testDFSWithCycle", testDFSWithCycle), ("testFindAllBfs", testFindAllBfs), + ("testFindAllBfsDoesNotRevisitStartVertex", testFindAllBfsDoesNotRevisitStartVertex), ("testFindAllDfs", testFindAllDfs), ("testTraverseBfsOnCycle", testTraverseBfsOnCycle), ("testTraverseDfsOnCycle", testTraverseDfsOnCycle),