Ctrl K

Surface of Cube Towers

Easy
An n × n board of unit cells holds towers of 1 × 1 × 1 cubes. The value heights[i][j] is how many cubes are stacked on cell (i, j) (0 means the cell is empty). All cubes that touch each other are glued together, forming one or more shapes. The shapes are going to be painted all over the outside, including the bottom faces resting on the board. Return the total surface area of all the shapes. Faces where two cubes press against each other do not count.
Example 1
heights=[[2, 0], [0, 1]] → 16

Two separate towers. The tower of 2 cubes has 4·2 side faces plus top and bottom, 10 in total. The single cube has 6. Together that is 16.

Example 2
heights=[[3, 1], [0, 0]] → 18

On their own the towers would give 14 + 6 = 20, but they stand side by side: one face of each touches the other, so 2 faces disappear. The answer is 18.

Example 3
heights=[[0]] → 0

No cubes, so the area is 0.

Constraints
  • 1 ≤ n ≤ 50
  • len(heights) = len(heights[i]) = n
  • 0 ≤ heights[i][j] ≤ 50
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShadows of Block Towers EasyHow a Rumor Spreads EasyThe Biggest Triangle on the Board EasyThree Stakes Off the Line EasyPosts in One Line Easy
loading Python…
Input
heights=[[2, 0], [0, 1]]
Expected
16

Run checks the first 3 tests in your browser. Submit checks all 76 tests on the server, hidden ones included.