-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d78325c
commit ad374ab
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,49 @@ | ||
/// BFS algorithm implementation. | ||
|
||
class Node { | ||
var name: String | ||
var children: [Node] | ||
|
||
init(name: String) { | ||
self.name = name | ||
children = [] | ||
} | ||
|
||
// Use `Set` to track previously visited nodes. | ||
var bfsVisited = Set<String>() | ||
|
||
func addChild(name: String) -> Node { | ||
let childNode = Node(name: name) | ||
children.append(childNode) | ||
|
||
return self | ||
} | ||
|
||
func breadthFirstSearch(array: inout [String]) -> [String] { | ||
bfsQueueTraversal(node: self, array: &array) | ||
return array | ||
} | ||
|
||
/// BFS traversal using `queue`. | ||
private func bfsQueueTraversal(node: Node, array: inout [String]) { | ||
var fakeQueue = [Node]() | ||
fakeQueue.append(node) // Init with node passed in | ||
|
||
while !fakeQueue.isEmpty { | ||
let currentNode = fakeQueue.removeFirst() | ||
|
||
// Skip previously visited node | ||
if bfsVisited.contains(currentNode.name) { continue } | ||
|
||
// Mark as visited | ||
bfsVisited.insert(currentNode.name) | ||
// Update array | ||
array.append(currentNode.name) | ||
|
||
// Use queue to process child nodes | ||
for childNode in currentNode.children { | ||
fakeQueue.append(childNode) | ||
} | ||
} | ||
} | ||
} |