Guest User

Untitled

a guest
Jul 22nd, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. 5 8
  2. ########
  3. #..#...#
  4. ####.#.#
  5. #..#...#
  6. ########
  7.  
  8. class UnionFind {
  9.  
  10. var parent: UnionFind?
  11. var rank: Int
  12.  
  13. init() {
  14. self.parent = nil
  15. self.rank = 0
  16. }
  17.  
  18. // Find with path compression
  19. func find() -> UnionFind {
  20. if let parent = self.parent {
  21. let p = parent.find()
  22. self.parent = p
  23. return p
  24. }
  25. return self
  26. }
  27.  
  28. // Combine the trees if the roots are distinct.
  29. // Returns `true` if the trees were combined, and
  30. // `false` if the trees already had the same root.
  31. @discardableResult func union(with other: UnionFind) -> Bool {
  32. var xRoot = self.find()
  33. var yRoot = other.find()
  34.  
  35. if xRoot === yRoot {
  36. return false
  37. }
  38.  
  39. if xRoot.rank < yRoot.rank {
  40. swap(&xRoot, &yRoot)
  41. }
  42.  
  43. // Merge yRoot into xRoot
  44. yRoot.parent = xRoot
  45. if xRoot.rank == yRoot.rank {
  46. xRoot.rank += 1
  47. }
  48. return true
  49. }
  50. }
  51.  
  52. import Foundation
  53.  
  54. func readDimensions() -> (height: Int, width: Int)? {
  55. guard let line = readLine() else { return nil }
  56. let ints = line.split(separator: " ")
  57. guard ints.count == 2,
  58. let height = Int(ints[0]),
  59. let width = Int(ints[1]) else {
  60. return nil
  61. }
  62. return (height, width)
  63. }
  64.  
  65. func readMapAndCountRooms(height: Int, width: Int) -> Int? {
  66. var tracker = Array<UnionFind?>(repeating: nil, count: width)
  67. var roomCount = 0
  68.  
  69. for _ in 0..<height {
  70. guard let line = readLine(), line.count == width else { return nil }
  71. for (offset, field) in line.enumerated() {
  72. if field == "." {
  73. if let top = tracker[offset] {
  74. // Continuation from the top ...
  75. if offset > 0, let left = tracker[offset - 1] {
  76. // ... and from the left:
  77. if top.union(with: left) {
  78. roomCount -= 1
  79. }
  80. }
  81. } else if offset > 0, let left = tracker[offset - 1] {
  82. // Continuation from the left:
  83. tracker[offset] = left
  84. } else {
  85. // New room:
  86. tracker[offset] = UnionFind()
  87. roomCount += 1
  88. }
  89. } else {
  90. // A wall:
  91. tracker[offset] = nil
  92. }
  93. }
  94. }
  95. return roomCount
  96. }
  97.  
  98. while let (height, width) = readDimensions(),
  99. let count = readMapAndCountRooms(height: height, width: width) {
  100. print(count)
  101. }
Add Comment
Please, Sign In to add comment