Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

892. Surface Area of 3D Shapes #83

Open
Tcdian opened this issue Mar 25, 2020 · 1 comment
Open

892. Surface Area of 3D Shapes #83

Tcdian opened this issue Mar 25, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Mar 25, 2020

892. Surface Area of 3D Shapes

在 N * N 的网格上,我们放置一些 1 * 1 * 1  的立方体。

每个值 v = grid[i][j] 表示 v 个正方体叠放在对应单元格 (i, j) 上。

请你返回最终形体的表面积。

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

Note

  • 1 <= N <= 50
  • 0 <= grid[i][j] <= 50
@Tcdian
Copy link
Owner Author

Tcdian commented Mar 25, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[][]} grid
 * @return {number}
 */
var surfaceArea = function(grid) {
    let result = 0;
    let direction = [-1, 0, 1, 0, -1];
    
    for (let i = 0 ; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            if (grid[i][j] !== 0) {
                result += grid[i][j] * 1 * 4 + 1 * 1 * 2;
                for (let d = 0; d < 4; d++) {
                    let directionX = i + direction[d];
                    let directionY = j + direction[d + 1];
                    if (directionX >= 0
                       && directionX < grid.length
                       && directionY >= 0
                       && directionY < grid.length
                    ) {
                        result -= Math.min(grid[i][j], grid[directionX][directionY]);
                    }
                }   
            }
        }
    }
    
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant