반응형
https://leetcode.com/problems/island-perimeter/description/
Island Perimeter - LeetCode
Can you solve this real interview question? Island Perimeter - You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
1. 4방향을 검사할 배열 dr, dc를 선언해줍니다.2. 정답을 반환할 변수 perimeter를 선언해줍니다.3. grid의 행 길이, 열 길이를 rLength와 cLength에 각각 저장해줍니다.
📔 풀이과정
1. grid를 2차원 loop로 순회하며 우, 좌, 하, 상 순으로 인접한 땅을 확인합니다.
2. 현재 땅의 둘레 길이는 4 - 인접한 땅 개수가 됩니다. 매 loop마다 4방향의 인접한 땅 개수를 세준 뒤 perimeter에 4 - 인접땅 개수를 누적해 더해줍니다.
📔 정답 출력 | 반환
둘레인 perimeter를 반환해줍니다.
📕 Code
📔 C++
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int dr[4] = {0,0,1,-1};
int dc[4] = {1,-1,0,0};
int perimeter = 0;
int rLength = grid.size();
int cLength = grid[0].size();
for(int i = 0; i < rLength; i++) {
for(int j = 0; j < cLength; j++) {
if(!grid[i][j]) continue;
int near = 0;
for(int dir = 0; dir < 4; dir++) {
int nr = i + dr[dir];
int nc = j + dc[dir];
if(0 > nr || nr >= rLength || 0 > nc || nc >= cLength) continue;
if(grid[nr][nc]) {
near++;
}
}
perimeter += 4 - near;
}
}
return perimeter;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Brute Force' 카테고리의 다른 글
(C++) - LeetCode (easy) 500. Keyboard Row (0) | 2023.04.04 |
---|---|
(C++) - LeetCode (easy) 496. Next Greater Element I (0) | 2023.04.03 |
(C++) - LeetCode (easy) 1539. Kth Missing Positive Number (0) | 2023.03.06 |
(C++) - LeetCode (easy) 401. Binary Watch (0) | 2023.03.03 |
(C++) - LeetCode (easy) 389. Find the Difference (0) | 2023.03.02 |