topic
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
Thinking
Initial idea is relatively simple to add this title are marked as easy, assume that the main body of the three-dimensional view, a left side view and a plan view of the sum is multiplied by 2 to result in the article "hollow" state (4,5 Example can not accurately calculate the surface area under). So think of other methods: Imagine that you walk on this three-dimensional body, from left to right, top to bottom traveled that is the surface area of the body. To achieve the following:
class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
int N=grid.size();
if(N==0)
return 0;
int ispan=0, jspan=0;
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
if(j==0)
jspan+=grid[i][j];
else
jspan+=abs(grid[i][j]-grid[i][j-1]);
if(grid[i][j] != 0)
jspan+=1;
if(j == N-1)
jspan+=grid[i][j];
if(i == 0)
ispan+=grid[i][j];
else
ispan+=abs(grid[i][j]-grid[i-1][j]);
if(grid[i][j] != 0)
ispan+=1;//加了两次,正好对应上面和下面
if(i == N-1)
ispan+=grid[i][j];
}
}
return ispan+jspan;
}
};