• + 0 comments

    Algo:

    • Take 2 times H*W, this is the top and bottom facing faces
    • Calculate left-right facing faces in a given row:
      • take first element
      • add absolute value of difference between each element
      • add last element
    • Calculate front-back facing faces in a given coloumn the same way

    C++ with going through the matrix only once:

    int surfaceArea(vector<vector<int>> A) {
        int area = 2 * A.size() * A[0].size();
        
        for(int i = 0; i < A.size(); i++){
            for(int j = 0; j < A[i].size(); j++){
    
                if(j == 0) area += A[i][j];
                if(j == A[i].size() - 1) area += A[i][j];
                if(j > 0 and j < A[i].size()) area += abs(A[i][j] - A[i][j-1]);
    
                if(i == 0) area += A[i][j];
                if(i == A.size() - 1) area += A[i][j];
                if(i > 0 and i < A.size()) area += abs(A[i][j] - A[i-1][j]);
            }
        }
    
        return area;
    }