All problems

Problem 994

Surface Area of 3D Shapes

Easy · 10 pts · Matrix, Math, Geometry

Problem

An N × N grid holds towers of unit cubes glued together: GRID[i][j] cubes stand on cell (i, j). Find the total surface area of the resulting shapes, including the bottom faces. A tower of height v > 0 has 4v + 2 faces on its own; then subtract the faces hidden between neighbouring towers, which is 2 × min(heights) for every pair of side-by-side cells.

Input

The first line contains N. Each of the next N lines contains N integers.

Output

Print the total surface area.

Constraints

1 <= N <= 50; 0 <= GRID[i][j] <= 50

Example input

2
1 2
3 4

Example output

34

Explanation

For 1 2 / 3 4, the towers alone have 6 + 10 + 14 + 18 = 48 faces. The shared faces hide 2 × (1 + 3 + 1 + 2) = 14, leaving 34.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Projection Area of 3D Shapes Next: Shift 2D Grid