Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node {
- var value: Int
- var visited = false
- init(value: Int = 0) {
- self.value = value
- }
- }
- class BreadthFirstSearch {
- var queue = [Node]()
- var nodes = [Node]()
- func findNeighbours(adjacenyMatrix: [[Int]], node: Node) -> [Node] {
- var currNodeIndex = -1
- var neighbours = [Node]()
- for i in 0..<nodes.count {
- if nodes[i].value == node.value {
- currNodeIndex = i
- break
- }
- }
- if currNodeIndex != -1 {
- for j in 0..<adjacenyMatrix[currNodeIndex].count {
- if adjacenyMatrix[currNodeIndex][j] == 1 {
- neighbours.append(nodes[j])
- }
- }
- }
- return neighbours
- }
- func bfs(head: Node? = nil, adjacencyMatrix: [[Int]]) {
- head?.visited = true
- queue.append(head!)
- while !queue.isEmpty {
- let node = queue.remove(at: 0)
- print(node.value)
- let neighbours = findNeighbours(adjacenyMatrix: adjacencyMatrix, node: node)
- for neighbour in neighbours {
- if !neighbour.visited {
- neighbour.visited = true
- queue.append(neighbour)
- }
- }
- }
- }
- }
- let node40 = Node(value: 40)
- let node10 = Node(value: 10)
- let node20 = Node(value: 20)
- let node30 = Node(value: 30)
- let node60 = Node(value: 60)
- let node50 = Node(value: 50)
- let node70 = Node(value: 70)
- var example = BreadthFirstSearch()
- example.nodes.append(node40)
- example.nodes.append(node10)
- example.nodes.append(node20)
- example.nodes.append(node30)
- example.nodes.append(node60)
- example.nodes.append(node50)
- example.nodes.append(node70)
- let adjacency_matrix =
- [
- [0,1,1,0,0,0,0], // Node 1: 40
- [0,0,0,1,0,0,0], // Node 2 :10
- [0,1,0,1,1,1,0], // Node 3: 20
- [0,0,0,0,1,0,0], // Node 4: 30
- [0,0,0,0,0,0,1], // Node 5: 60
- [0,0,0,0,0,0,1], // Node 6: 50
- [0,0,0,0,0,0,0], // Node 7: 70
- ]
- example.bfs(head: node40, adjacencyMatrix: adjacency_matrix)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement