Created
April 16, 2018 01:44
-
-
Save LucianoPAlmeida/7b31c98fa554ef53085580f47027dacc to your computer and use it in GitHub Desktop.
Understanding and implementing a BFS algorithm.
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
class Node: CustomStringConvertible { | |
var tagged: Bool | |
var name: String = "" | |
var subnodes: [Node] = [] | |
init(tagged: Bool, name: String = "") { | |
self.tagged = tagged | |
self.name = name | |
} | |
func add(_ node: Node) { | |
subnodes.append(node) | |
} | |
func findTagged() -> Node? { | |
var nodes = [Node](arrayLiteral: self) | |
var i = 0 | |
repeat { | |
let n = nodes[i] | |
if n.tagged { | |
return n | |
} | |
nodes.append(contentsOf: n.subnodes) | |
i += 1 | |
} while i < nodes.count | |
return nil | |
} | |
var description: String { | |
return "\(name): \(tagged)" | |
} | |
} | |
var root = Node(tagged: false, name: "root") | |
var sub1 = Node(tagged: false, name: "sub1") | |
var sub2 = Node(tagged: false, name: "sub2") | |
var subsub1 = Node(tagged: false, name: "subsub1") | |
var deep = Node(tagged: true, name: "deep") | |
subsub1.add(deep) | |
root.add(sub1) | |
sub2.add(subsub1) | |
root.add(sub2) | |
let tagged = root.findTagged() | |
print(tagged) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment