• + 0 comments

    Swift:

    func surfaceArea(A: [[Int]]) -> Int {
        // Write your code here
        let H: Int = A.count - 1
        let W: Int = A.first!.count - 1
        
        var totalSurface: Int = 0
        
        for index1 in 0 ... W {
            var lastNumberLeft = 0
            var lastNumberRight = 0
            
            for index2 in 0 ... H {
                // calculate left facing cube
                if A[index2][index1] > lastNumberLeft {
                    totalSurface += A[index2][index1] - lastNumberLeft
                }
                lastNumberLeft = A[index2][index1] 
                
                // calculate right facing cube
                if A[H - index2][W - index1] > lastNumberRight {
                    totalSurface += A[H - index2][W - index1] - lastNumberRight
                }
                lastNumberRight = A[H - index2][W - index1]
            }
        }
        
        
        for index1 in 0 ... H {
            var lastNumberFront = 0
            var lastNumberBack = 0
            
            for index2 in 0 ... W {
                // calculate front facing cube
                if A[index1][index2] > lastNumberFront {
                   totalSurface += A[index1][index2] - lastNumberFront 
                }
                lastNumberFront = A[index1][index2]
    
                // calculate back facing cube
                if A[H - index1][W - index2] > lastNumberBack {
                   totalSurface += A[H - index1][W - index2] - lastNumberBack 
                }
                lastNumberBack = A[H - index1][W - index2]
            }
        }
        
        return ((H + 1) * (W + 1)) * 2 + totalSurface
    }