Advertisement
Guest User

Untitled

a guest
May 19th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. class Node {
  2. var value: Int
  3. var visited = false
  4.  
  5. init(value: Int = 0) {
  6. self.value = value
  7. }
  8. }
  9.  
  10. class BreadthFirstSearch {
  11. var queue = [Node]()
  12. var nodes = [Node]()
  13.  
  14. func findNeighbours(adjacenyMatrix: [[Int]], node: Node) -> [Node] {
  15. var currNodeIndex = -1
  16. var neighbours = [Node]()
  17.  
  18. for i in 0..<nodes.count {
  19. if nodes[i].value == node.value {
  20. currNodeIndex = i
  21. break
  22. }
  23. }
  24.  
  25. if currNodeIndex != -1 {
  26. for j in 0..<adjacenyMatrix[currNodeIndex].count {
  27. if adjacenyMatrix[currNodeIndex][j] == 1 {
  28. neighbours.append(nodes[j])
  29. }
  30. }
  31. }
  32.  
  33. return neighbours
  34. }
  35.  
  36. func bfs(head: Node? = nil, adjacencyMatrix: [[Int]]) {
  37. head?.visited = true
  38. queue.append(head!)
  39.  
  40. while !queue.isEmpty {
  41. let node = queue.remove(at: 0)
  42. print(node.value)
  43.  
  44. let neighbours = findNeighbours(adjacenyMatrix: adjacencyMatrix, node: node)
  45. for neighbour in neighbours {
  46. if !neighbour.visited {
  47. neighbour.visited = true
  48. queue.append(neighbour)
  49. }
  50. }
  51. }
  52. }
  53. }
  54.  
  55. let node40 = Node(value: 40)
  56. let node10 = Node(value: 10)
  57. let node20 = Node(value: 20)
  58. let node30 = Node(value: 30)
  59. let node60 = Node(value: 60)
  60. let node50 = Node(value: 50)
  61. let node70 = Node(value: 70)
  62.  
  63. var example = BreadthFirstSearch()
  64. example.nodes.append(node40)
  65. example.nodes.append(node10)
  66. example.nodes.append(node20)
  67. example.nodes.append(node30)
  68. example.nodes.append(node60)
  69. example.nodes.append(node50)
  70. example.nodes.append(node70)
  71.  
  72. let adjacency_matrix =
  73. [
  74. [0,1,1,0,0,0,0], // Node 1: 40
  75. [0,0,0,1,0,0,0], // Node 2 :10
  76. [0,1,0,1,1,1,0], // Node 3: 20
  77. [0,0,0,0,1,0,0], // Node 4: 30
  78. [0,0,0,0,0,0,1], // Node 5: 60
  79. [0,0,0,0,0,0,1], // Node 6: 50
  80. [0,0,0,0,0,0,0], // Node 7: 70
  81. ]
  82.  
  83. example.bfs(head: node40, adjacencyMatrix: adjacency_matrix)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement