Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 5 8
- ########
- #..#...#
- ####.#.#
- #..#...#
- ########
- class UnionFind {
- var parent: UnionFind?
- var rank: Int
- init() {
- self.parent = nil
- self.rank = 0
- }
- // Find with path compression
- func find() -> UnionFind {
- if let parent = self.parent {
- let p = parent.find()
- self.parent = p
- return p
- }
- return self
- }
- // Combine the trees if the roots are distinct.
- // Returns `true` if the trees were combined, and
- // `false` if the trees already had the same root.
- @discardableResult func union(with other: UnionFind) -> Bool {
- var xRoot = self.find()
- var yRoot = other.find()
- if xRoot === yRoot {
- return false
- }
- if xRoot.rank < yRoot.rank {
- swap(&xRoot, &yRoot)
- }
- // Merge yRoot into xRoot
- yRoot.parent = xRoot
- if xRoot.rank == yRoot.rank {
- xRoot.rank += 1
- }
- return true
- }
- }
- import Foundation
- func readDimensions() -> (height: Int, width: Int)? {
- guard let line = readLine() else { return nil }
- let ints = line.split(separator: " ")
- guard ints.count == 2,
- let height = Int(ints[0]),
- let width = Int(ints[1]) else {
- return nil
- }
- return (height, width)
- }
- func readMapAndCountRooms(height: Int, width: Int) -> Int? {
- var tracker = Array<UnionFind?>(repeating: nil, count: width)
- var roomCount = 0
- for _ in 0..<height {
- guard let line = readLine(), line.count == width else { return nil }
- for (offset, field) in line.enumerated() {
- if field == "." {
- if let top = tracker[offset] {
- // Continuation from the top ...
- if offset > 0, let left = tracker[offset - 1] {
- // ... and from the left:
- if top.union(with: left) {
- roomCount -= 1
- }
- }
- } else if offset > 0, let left = tracker[offset - 1] {
- // Continuation from the left:
- tracker[offset] = left
- } else {
- // New room:
- tracker[offset] = UnionFind()
- roomCount += 1
- }
- } else {
- // A wall:
- tracker[offset] = nil
- }
- }
- }
- return roomCount
- }
- while let (height, width) = readDimensions(),
- let count = readMapAndCountRooms(height: height, width: width) {
- print(count)
- }
Add Comment
Please, Sign In to add comment