• + 0 comments

    JS:

    function surfaceArea(A) {
      if (A.length === 1 && A[0] === 1) return 6;
    
      let surface = 0;
    
      for (let row = 0; row < A.length; row++) {
        const currentRow = A[row];
        for (let col = 0; col < currentRow.length; col++) {
          const height = currentRow[col];
    
          // Add top and bottom surfaces
          surface += 2;
    
          // Add side surfaces
          const neighbors = [
            row > 0 ? A[row - 1][col] : 0, // Front
            row < A.length - 1 ? A[row + 1][col] : 0, // Back
            col > 0 ? currentRow[col - 1] : 0, // Left
            col < currentRow.length - 1 ? currentRow[col + 1] : 0, // Right
          ];
    
          for (const neighbor of neighbors) {
            surface += Math.max(0, height - neighbor);
          }
        }
      }
    
      return surface;
    }