Surface Area of 3D Shapes

本文介绍了一种计算由1x1x1立方体组成的三维形状表面总面积的方法。通过两种不同的算法实现:一种是遍历每个点统计四个方向上的侧面积;另一种是先计算所有表面面积再减去重复计算的部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

Example 1:

Input: [[2]]
Output: 10

Example 2:

Input: [[1,2],[3,4]]
Output: 34

 

// 上下面积都是 size*size 关键是侧面积
// 遍历每个点 统计四个方向上的侧面积(如果周围没有则直接加上这个高度)

// 另一种思路 算上所有的  减去多算的 (值考虑左和上)
class Solution {
public:
    int surfaceArea(vector<vector<int>>& grid) {
        int w=grid[0].size(), h=grid.size();
        vector<pair<int, int>> walk={{1,0},{-1,0},{0,1}, {0,-1}};
        int area=0, cnt=0;
        for(int j=0;j<h;j++){
            for(int i=0;i<w;i++){
                for(int k=0;k<4;k++){
                    if(grid[j][i] != 0) cnt++;
                    int tmpj = j+walk[k].first, tmpi= i+walk[k].second;
                    if(tmpj==h || tmpj<0 || tmpi==w || tmpi<0)  area += grid[j][i];
                    else if(grid[j][i] > grid[tmpj][tmpi])  area += grid[j][i] - grid[tmpj][tmpi];
                }
            }
        }
        area += cnt*2;
        return area;
    }
};
lass Solution {
public:
    int surfaceArea(vector<vector<int>>& grid) {
        int res = 0, n = grid.size();
        for (int i = 0; i < n; ++i) 
        {
            for (int j = 0; j < n; ++j) 
            {
                // get all surface 
                if (grid[i][j]) 
                    res += grid[i][j] * 4 + 2;
                // remove above and left attaching surface
                if (i) 
                    res -= min(grid[i][j], grid[i - 1][j]) * 2;
                if (j) 
                    res -= min(grid[i][j], grid[i][j - 1]) * 2;
            }
        }
        return res;
    }
};

 

### Alpha Shapes算法在Python中的实现 Alpha Shapes 是一种用于计算几何形状的技术,它可以根据一组离散点生成具有特定拓扑结构的多边形或多面体。以下是基于 Python 的 Alpha Shapes 实现方法及其应用。 #### 使用 `scipy` 和自定义函数实现 Alpha Shapes 可以利用 `scipy.spatial.Delaunay` 来构建 Delaunay 三角剖分,并通过调整参数 α 控制形状复杂度。以下是一个完整的代码示例: ```python import numpy as np from scipy.spatial import Delaunay import matplotlib.pyplot as plt def alpha_shape(points, alpha): """ 计算给定点集的 Alpha Shape。 参数: points (list of tuples): 输入点集 [(x1, y1), (x2, y2), ...] alpha (float): Alpha 值 返回: edges (set): 边集合 """ tri = Delaunay(points) edges = set() def add_edge(i, j): """ 添加一条有序边到集合中 """ if (i, j) not in edges and (j, i) not in edges: edges.add((i, j)) # 遍历所有三角形并筛选符合条件的边 for ia, ib, ic in tri.vertices: pa = points[ia] pb = points[ib] pc = points[ic] # 计算外接圆半径 a = np.linalg.norm(pa - pb) b = np.linalg.norm(pb - pc) c = np.linalg.norm(pc - pa) s = (a + b + c) / 2.0 area = abs(a * b * c / 4.0 / np.sqrt(s * (s - a) * (s - b) * (s - c))) circum_r = a * b * c / (4.0 * area) if circum_r < 1.0 / alpha: add_edge(ia, ib) add_edge(ib, ic) add_edge(ic, ia) return edges # 测试数据 points = np.random.rand(20, 2) edges = alpha_shape(points.tolist(), alpha=0.2) # 绘图 plt.figure(figsize=(8, 6)) for edge in edges: i, j = edge p1, p2 = points[[i, j]] plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'k-') plt.scatter(points[:, 0], points[:, 1], marker='o', color='blue') plt.title("Alpha Shape Example") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.axis('equal') plt.show() ``` 上述代码实现了 Alpha Shapes 算法的核心逻辑[^1],并通过绘制图形展示了其效果。 --- #### 利用第三方库 `alphashape` 除了手动实现之外,还可以借助专门设计的库来简化开发流程。例如,`alphashape` 库提供了高效的 API 接口。 安装方式如下: ```bash pip install alphashape ``` 使用示例: ```python import alphashape import matplotlib.pyplot as plt import numpy as np # 创建随机点集 points = np.random.uniform(low=-10, high=10, size=(30, 2)) # 构建 Alpha Shape alpha = 2.0 shape = alphashape.alphashape(points, alpha) # 提取边界坐标 boundary_points = shape.boundary.coords.xy # 绘图 fig, ax = plt.subplots() ax.fill(*boundary_points, alpha=0.2, fc='orange', ec='red') ax.scatter(points[:, 0], points[:, 1]) plt.title("Alpha Shape with Alphashape Library") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.axis('equal') plt.show() ``` 此方法更加简洁明了,适合快速原型验证和实际项目部署[^4]。 --- #### PCLPy 中的应用 对于三维点云处理场景,PCL(Point Cloud Library)提供了一个强大的工具链支持 Alpha Shapes 算法。可以通过 `pclpy` 将其实现于 Python 脚本中[^3]。 安装依赖项: ```bash conda install pcl py-pcl -c conda-forge ``` 简单示例: ```python import pclpy from pclpy import pcl # 加载点云数据 cloud = pcl.PointCloud.PointXYZ.from_file("point_cloud.pcd") # 初始化 Alpha Shapes 对象 search_method = pcl.search.KdTreeFLANN.PointXYZ() as_estimator = pcl.surface.AlphaShapes(cloud, search_method) # 设置 Alpha 值 as_estimator.setAlphaValue(0.5) # 执行估计操作 indices = [] coefficients = [] as_estimator.compute(indices, coefficients) print(f"Edge Indices: {indices}") print(f"Coefficients: {coefficients}") ``` 以上代码片段演示了如何结合 PCLPy 进行三维点云边界提取。 --- ### 总结 无论是二维还是三维空间,Alpha Shapes 算法都可以灵活应用于各种领域。具体实现可根据需求选择手写核心逻辑或者调用成熟框架完成任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值