• + 0 comments

    SWIFT

    func cavityMap(grid: [String]) -> [String] {
        // Write your code here
        if grid.first!.count < 3 { return grid }
        
        var gridUTF8: [[UInt8]] = grid.map{ [UInt8]($0.utf8) }
        
        let gridMaxIndex: Int = gridUTF8.count - 1
        let gridContentMaxIndex: Int = gridUTF8.first!.count - 1
        
        for index1 in 1 ... gridMaxIndex - 1 {
            for index2 in 1 ... gridContentMaxIndex - 1 {
                let currentGrid: UInt8 = gridUTF8[index1][index2]
                let isHValid: Bool = gridUTF8[index1][index2 - 1] < currentGrid && gridUTF8[index1][index2 + 1] < currentGrid
                let isVValid: Bool = gridUTF8[index1 - 1][index2] < currentGrid && gridUTF8[index1 + 1][index2] < currentGrid
                if isHValid && isVValid  {
                    gridUTF8[index1][index2] = 88
                    continue
                }
            }
        }
        
        return gridUTF8.map{ String(bytes: $0, encoding: String.Encoding.utf8) ?? "" }
    }