본문 바로가기

Algorithm/Implementation

(C++, Rust) - LeetCode (easy) 892. Surface Area of 3D Shapes

반응형

https://leetcode.com/problems/surface-area-of-3d-shapes/description/

 

Surface Area of 3D Shapes - LeetCode

Can you solve this real interview question? Surface Area of 3D Shapes - You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j). After placing these cubes,

leetcode.com

공간지각능력 문제였습니다?

📕 풀이방법

📔 입력 및 초기화

1. 인접한 동서남북 4방향을 확인하기 위한 배열 dr, dc를 선언해줍니다.2. 정답변수 ans를 선언, 0으로 초기화 해줍니다.

📔 풀이과정

grid의 모든 원소를 확인하며 확인 때마다 인접 4곳을 확인해줍니다. 매 원소마다 다음과 같은 과정을 수행해 ans에 더해줍니다.1. 가장자리인 경우: 옆면은 쌓인 cube의 높이가 됩니다. 해당 값만큼 더해줍니다.2. 인접 cube보다 현재 확인하고 있는 grid의 높이가 높다면 차이만큼 옆면을 더해줍니다.3. 현재 grid가 양수라면 위와 아래면을 더해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int dr[4] = {0,0,1,-1};
    int dc[4] = {1,-1,0,0};
    int surfaceArea(vector<vector<int>>& grid) {
        int ans = 0;
        int height = grid.size();
        int width = grid[0].size();
        for(int r = 0; r < height; r++) {
            for(int c = 0; c < width; c++) {
                int cnt = 0;
                for(int dir = 0; dir < 4; dir++) {
                    int nr = r + dr[dir];
                    int nc = c + dc[dir];
                    if(0 > nr || nr >= height || 0 > nc || nc >= width) {
                        ans += grid[r][c]; continue; //가장자리면
                    }
                    if(grid[r][c] > grid[nr][nc])
                        ans += grid[r][c] - grid[nr][nc]; //옆면
                }
                if(grid[r][c]) ans += 2; //윗면 아랫면
            }
        }
        return ans;
    }
};

📔 Rust

impl Solution {
    pub fn surface_area(grid: Vec<Vec<i32>>) -> i32 {
        let n = grid.len();
        let mut ans = 0;
        let dr: [i32; 4] = [0, 0, 1, -1];
        let dc: [i32; 4] = [1, -1, 0, 0];
        for r in 0..n {
            for c in 0..n {
                for dir in 0..4 {
                    let nr = r as i32 + dr[dir];
                    let nc = c as i32 + dc[dir];
                    if nr < 0 || nr >= n as i32 || nc < 0 || nc >= n as i32 {
                        ans += grid[r][c];
                        continue;
                    }
                    if grid[r][c] > grid[nr as usize][nc as usize] {
                        ans += grid[r][c] - grid[nr as usize][nc as usize];
                    }
                }
                if grid[r][c] > 0 {
                    ans += 2;
                }
            }
        }
        return ans;
    }
}

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.