Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Surface Area of 3D Shapes (พื้นที่ผิวรูปทรง 3D) ใน Python

โจทย์: ให้ Grid N×N ค่า v = grid[i][j] แทนหอคอยลูกบาศก์ 1×1×1 สูง v ชิ้น หาพื้นที่ผิวรวมของรูปทรงที่ได้

Input/Output

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

สูตรคำนวณ

พื้นที่ผิวรวม = พื้นที่ Top/Bottom + พื้นที่ Side (4 ด้าน) - พื้นที่ที่ติดกัน (Internal faces)

  • Top/Bottom: 2 × (จำนวนเซลล์ที่ v > 0)
  • Side faces: 4 × (ผลรวมความสูงทั้งหมด)
  • Internal faces (ลบออก): 2 × min(h1, h2) สำหรับแต่ละคู่เซลล์ติดกัน (แนวนอน + แนวตั้ง)

ตัวอย่างโค้ด

class Solution:
    def surfaceArea(self, grid):
        def adjacentArea(row):
            area = 0
            for i in range(len(row) - 1):
                if row[i] and row[i + 1]:
                    area += 2 * min(row[i], row[i+1])
            return area
        
        # Top + Bottom
        z = sum([sum(1 for i in row if i > 0) for row in grid]) * 2
        # 4 Side faces
        x_plus_y = sum([sum(row) for row in grid]) * 4
        # Internal horizontal adjacency
        x_adjacent = sum([adjacentArea(row) for row in grid])
        # Internal vertical adjacency (Transpose grid)
        y_adjacent = sum([adjacentArea(row) for row in zip(*grid)])
        
        return z + (x_plus_y - x_adjacent - y_adjacent)

ob = Solution()
print(ob.surfaceArea([[1, 2], [3, 4]]))

ผลลัพธ์

34

การคำนวณตัวอย่าง [[1,2],[3,4]]:

  • Top/Bottom: 4 cells × 2 = 8
  • Side: (1+2+3+4) × 4 = 40
  • Horizontal adj: min(1,2)×2 + min(3,4)×2 = 2+6 = 8
  • Vertical adj: min(1,3)×2 + min(2,4)×2 = 2+4 = 6
  • Total: 8 + 40 - 8 - 6 = 34 ✓