
问题
在 N * N 的网格上,我们放置一些 1 * 1 * 1 的立方体。
每个值 v = grid[i][j] 表示 v 个正方体叠放在单元格 (i, j) 上。
返回结果形体的总表面积。
输入:[[2]]
输出:10
示例 2:输入:[[1,2],[3,4]]
输出:34
示例 3:输入:[[1,0],[0,2]]
输出:16
示例 4:输入:[[1,1,1],[1,0,1],[1,1,1]]
输出:32
示例 5:输入:[[2,2,2],[2,1,2],[2,2,2]]
输出:46
提示:
- 1 <= N <= 50
- 0 <= grid[i][j] <= 50
On a N * N grid, we place some 1 * 1 * 1 cubes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
Return the total surface area of the resulting shapes.
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
示例
public class Program { public static void Main(string[] args) { var grid = new int[][] { new int[] { 2 } }; var res = SurfaceArea(grid); Console.WriteLine(res); Console.ReadKey(); } public static int SurfaceArea(int[][] grid) { var res = 0; for(var i = 0; i < grid.Length; i++) for(var j = 0; j < grid[0].Length; j++) { if(grid[i][j] > 0) //若有立方体,总的表面积为立方体的 4 个边加上下底 res += 4 * grid[i][j] + 2; if(i < grid.Length - 1) //若在 x 轴上,不是 x 轴上的最后一个 //那么减去它们重叠的部分 * 2 res -= Math.Min(grid[i][j], grid[i + 1][j]) * 2; if(j < grid[0].Length - 1) //若在 y 轴上,不是 y 轴上的最后一个 //那么减去它们重叠的部分 * 2 res -= Math.Min(grid[i][j], grid[i][j + 1]) * 2; } return res; } }
以上给出1种算法实现,以下是这个案例的输出结果:
10
分析:
显而易见,以上算法的时间复杂度为: 。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/4136。