OO DFS solution, easy to read, in swift


  • 0
    S
    class Island {
    
      var visited = false
      var portal = false
      var neighbors = [Island]()
    
      func visit(portal: Bool) {
        if visited { return }
        visited = true
        self.portal = portal
        neighbors.forEach { neighbor in
          neighbor.visit(false)
        }
      }
    
    }
    
    
    class Solution {
    
      func numIslands(grid: [[Character]]) -> Int {
        guard grid.count > 0 else { return 0 }
        var islandNum = 0
        var islands = [String: Island]()
        for i in 0..<grid.count {
          for j in 0..<grid[i].count {
            guard grid[i][j] == "1" else { continue }
            let island = Island()
            islands["\(i),\(j)"] = island
            let north = islands["\(i - 1),\(j)"]
            let west = islands["\(i),\(j - 1)"]
            [north, west].forEach { neighbor in
              if neighbor != nil {
                let neighbor = neighbor!
                neighbor.neighbors.append(island)
                island.neighbors.append(neighbor)
              }
            }
          }
        }
    
        for (_, island) in islands {
          island.visit(true)
          if island.portal {
            islandNum += 1
          }
        }
    
        return islandNum
      }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.