← 返回博客列表
Snap

Snap 幾何演算法面試:計算不規則建築群的外圍周長

2025-08-11

Snap 面試中的幾何演算法題。本文通過建築物周長計算問題,展示如何處理二維網格上的幾何問題,oavoservice 助你掌握幾何演算法核心技巧。

📋 問題重新定義

給定一個二維網格,其中 1 表示建築物,0 表示空地。建築物可能連接形成不規則形狀。計算所有建築物的外圍周長(只計算與空地或邊界接觸的邊)。

範例:

Input: grid = [
  [1,1,0],
  [1,1,0],
  [0,0,1]
]
Output: 12

🎯 核心思路

  1. 邊界識別 - 找出所有與空地接觸的邊
  2. 去重處理 - 避免重複計算共享邊
  3. 邊界情況 - 處理網格邊緣
  4. 優化策略 - 減少不必要的遍歷

💡 解題方法(oavoservice 創新解法)

方法一:直接計數法

def calculate_perimeter(grid):
    if not grid or not grid[0]:
        return 0
    
    rows, cols = len(grid), len(grid[0])
    perimeter = 0
    
    for i in range(rows):
        for j in range(cols):
            if grid[i][j] == 1:
                # 檢查四個方向
                if i == 0 or grid[i-1][j] == 0:
                    perimeter += 1
                if i == rows-1 or grid[i+1][j] == 0:
                    perimeter += 1
                if j == 0 or grid[i][j-1] == 0:
                    perimeter += 1
                if j == cols-1 or grid[i][j+1] == 0:
                    perimeter += 1
    
    return perimeter

時間複雜度: O(m × n) 空間複雜度: O(1)

方法二:數學優化

oavoservice 提供的優化思路:

def calculate_perimeter_optimized(grid):
    rows, cols = len(grid), len(grid[0])
    buildings = 0
    shared_edges = 0
    
    for i in range(rows):
        for j in range(cols):
            if grid[i][j] == 1:
                buildings += 1
                
                # 檢查右邊和下邊的共享邊
                if j < cols - 1 and grid[i][j+1] == 1:
                    shared_edges += 1
                if i < rows - 1 and grid[i+1][j] == 1:
                    shared_edges += 1
    
    # 每個建築貢獻4條邊,減去共享邊(每條共享邊被兩個方塊共用,所以減2)
    return buildings * 4 - shared_edges * 2

🚀 擴展問題

1. 3D 建築物表面積

def calculate_surface_area_3d(grid):
    """
    grid[i][j] 表示該位置建築物的高度
    """
    if not grid:
        return 0
    
    rows, cols = len(grid), len(grid[0])
    surface_area = 0
    
    for i in range(rows):
        for j in range(cols):
            if grid[i][j] > 0:
                # 頂部和底部
                surface_area += 2
                
                # 四個側面
                for di, dj in [(0,1), (0,-1), (1,0), (-1,0)]:
                    ni, nj = i + di, j + dj
                    neighbor_height = 0
                    
                    if 0 <= ni < rows and 0 <= nj < cols:
                        neighbor_height = grid[ni][nj]
                    
                    # 當前建築高於鄰居的部分貢獻表面積
                    if grid[i][j] > neighbor_height:
                        surface_area += grid[i][j] - neighbor_height
    
    return surface_area

💼 oavoservice 助力

幾何思維 - 將問題轉化為幾何計算 優化策略 - 數學方法減少計算 擴展能力 - 3D 和複雜場景 程式碼實作 - 清晰的邏輯結構

聯繫 oavoservice,專業幾何演算法面試輔助!


標籤: #Snap #幾何演算法 #網格遍歷 #VO輔助 #面試輔助 #一畝三分地


需要面試真題? 立刻聯繫微信 Coding0201獲得真題