每日一題-5.三維形體的表面積

題目:

在 N * N 的網格上,我們放置一些 1 * 1 * 1 的立方體。

每個值 v = grid[i][j] 表示 v 個正方體疊放在對應單元格 (i, j) 上。

請你返回最終形體的表面積。

思考:

首先將二維座標系中的所有方塊按照獨立的進行計算表面積,即方塊數*6,然後計算需要減去的值,兩個方塊相連,表面積減去2,即分爲兩步,
1.當前座標本身,需要減去的表面積爲:(方塊數-1)*2;
2.當前座標左邊需要減去的表面積爲:min(左邊方塊數,當前方塊數)*2;
3.當前座標上邊需要減去的表面積爲:min(上邊方塊數,當前方塊數)*2;

class Solution {
    public int surfaceArea(int[][] grid) {
        int result = 0;
        int temp = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                result += grid[i][j]*6;
                //座標點不止一個元素時
                if(grid[i][j]>0) {
                    temp += (grid[i][j] - 1) * 2;
                    //二維座標系最上邊一行
                    if(i==0&&j>0){
                        if(grid[i][j-1]>0){
                            temp += Math.min(grid[i][j],grid[i][j-1])*2;
                        }
                    }
                    //二維座標系最最左邊一行
                    if(i>0&&j==0){
                        if(grid[i-1][j]>0){
                            temp += Math.min(grid[i][j],grid[i-1][j])*2;
                        }
                    }
                    //二維座標系其他元素
                    if(i>0&&j>0){
                        if(grid[i][j-1]>0){
                            temp += Math.min(grid[i][j],grid[i][j-1])*2;
                        }
                        if(grid[i-1][j]>0){
                            temp += Math.min(grid[i][j],grid[i-1][j])*2;
                        }
                    }
                }
            }
        }
        return result - temp;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章