Developer/LEETCODE
463. Island Perimeter
cepiloth
2021. 10. 5. 06:30
728x90
https://leetcode.com/problems/island-perimeter/
Island Perimeter - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com

문제
1로 채워진 부분이 섬이고 섬에 둘레는 구하여라.
해당문제는 length 의 길이가 100 임으로 최대 100 x 100 크기의 배열이 입력으로 들어온다. DFS 를 통하여 1인 지역내에서 주변에 이어진 섬이 있는지 체크하여 count 변수를 체크 하였다.
소스코드
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int count = 0;
int rows = grid.size();
int cols = grid[0].size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 1)
{
count += 4;
if (i - 1 >= 0 && grid[i - 1][j]) count--;
if (i + 1 < rows && grid[i + 1][j]) count--;
if (j - 1 >= 0 && grid[i][j - 1]) count--;
if (j + 1 < cols && grid[i][j + 1]) count--;
}
}
}
return count;
}
};728x90
반응형