91. The three-dimensional body surface area
Topic Link
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/surface-area-of-3d-shapes
Title Description
N * N on the grid, we put some cube 1 * 1 * 1.
Each value v = grid [i] [j] denotes the v cube superposed on the corresponding cell (i, j).
Please return to the final body surface area.
Example 1:
Input: [[2]]
Output: 10
Example 2:
Input: [[1,2], [3,4]]
Output: 34
Example 3:
Input: [[1,0], [0,2]]
Output: 16
Example 4:
Input: [[1,1,1], [1,0,1], [1,1,1]]
Output: 32
Example 5:
Input: [[2,2,2], [2,1,2], [2,2,2]]
Output: 46
prompt:
1 <= N <= 50
0 <= grid[i][j] <= 50
Heavy and difficult
- Read the title.
- Considering the bonding surface.
Topic analysis
- Reading problems, Analysis Example 1: (0,0) position has two cubes together, so that a surface area of 2 * 4 + 2 = 10;
- Reading problems, Analysis Example 2: There is a cube (0,0) position, together with a two cubes (0,1) position, there are three in the (1,0) position cubes together, together with four cubes at location (1,1) is on.
- Surface area of a cube for each position is: 2 +4 bottom surface side, if a stacked position on the two cubes is: 2 + 8 bottom surface side;
- Cube adjacent positions after the release, there will be a bonding surface for each position, the surface area should subtract stick together face * 2.
/** * @param {number[][]} grid * @return {number} */ var surfaceArea = function(grid) { if(grid === [[0]] ) return 0; let n = grid.length; let res = 0; for(let i=0;i<n;i++){ for(let j=0;j<n;j++){ res += grid[i][j] > 0 ? (4*grid[i][j]+2) : 0; // subtract two surface area i and i + 1 with stickers res -= (i<n-1 && grid[i+1][j] > 0) ? 2 * Math.min(grid[i][j],grid[i+1][j]) : 0; // subtract two surface area j and j + 1 phase affixed res -= (j<n-1 && grid[i][j+1] > 0) ? 2 * Math.min(grid[i][j],grid[i][j+1]) : 0; } } return res; };