Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the Surface area of a 3D figure in Python
Finding the surface area of a 3D figure represented by a matrix involves calculating the exposed surfaces of each building block. Each cell A[i][j] represents the height of a building at position (i, j).
Algorithm
The surface area calculation considers ?
Top and bottom surfaces ? Each cell contributes 2 units (top and bottom)
Side surfaces ? Calculate height differences between adjacent cells
Border surfaces ? Add full height for cells at matrix edges
Step-by-Step Approach
Initialize result = 0
For each cell (i, j), calculate height differences with top and left neighbors
Add exposed surfaces for bottom and right edges
Add top and bottom surfaces for all cells
Implementation
def get_surface_area(array, N, M):
res = 0
for i in range(N):
for j in range(M):
up_side = 0
left_side = 0
# Check adjacent cells
if i > 0:
up_side = array[i - 1][j]
if j > 0:
left_side = array[i][j - 1]
# Add side surface differences
res += abs(array[i][j] - up_side) + abs(array[i][j] - left_side)
# Add edge surfaces
if i == N - 1: # Bottom edge
res += array[i][j]
if j == M - 1: # Right edge
res += array[i][j]
# Add top and bottom surfaces for all cells
res += N * M * 2
return res
# Example usage
N = 3
M = 3
array = [[1, 4, 5], [3, 3, 4], [1, 3, 5]]
surface_area = get_surface_area(array, N, M)
print(f"Surface area: {surface_area}")
Surface area: 72
How It Works
The algorithm calculates surface area by ?
Side differences ?
|current_height - neighbor_height|gives exposed vertical surfaceEdge contributions ? Cells at bottom and right edges contribute their full height
Top/bottom ? Each cell contributes 2 units (1 for top, 1 for bottom)
Example Calculation
For the 3×3 matrix [[1,4,5],[3,3,4],[1,3,5]] ?
| Component | Calculation | Value |
|---|---|---|
| Side surfaces | Height differences between neighbors | 54 |
| Top/Bottom | 3 × 3 × 2 = 18 | 18 |
| Total | 54 + 18 | 72 |
Conclusion
This algorithm efficiently calculates 3D surface area by considering height differences between adjacent cells and adding contributions from all exposed faces. The time complexity is O(N×M) for processing each cell once.
