leetcode 892 三維形體的表面積
思路和官網提供的一致
程式碼(粗糙,沒有用到庫裡的函式,if else太多,暫時沒有找到好的改進方法,因為方塊是不是在邊界必須得要去判斷)
class Solution { public: int surfaceArea(vector<vector<int>>& grid) { int result = 0; int row = grid.size(); int col = grid[0].size(); for(int i =0; i < row; i++) { for(int j = 0; j < col; j++) { if(grid[i][j] != 0) { result += 2; if(i - 1 >= 0) { result += (grid[i][j] > grid[i-1][j])?grid[i][j]-grid[i-1][j]:0; }else result += grid[i][j]; if(i + 1 < row) { result += (grid[i][j] > grid[i+1][j])?grid[i][j]-grid[i+1][j]:0; }else result += grid[i][j]; if(j - 1 >= 0) { result += (grid[i][j] > grid[i][j-1])?grid[i][j]-grid[i][j-1]:0; }else result += grid[i][j]; if(j + 1 < col) { result += (grid[i][j] > grid[i][j+1])?grid[i][j]-grid[i][j+1]:0; }else result += grid[i][j]; } } } return result; } };