[LeetCode] Island Perimeter

463. 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 is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).

The island doesn’t have “lakes”, meaning the water inside isn’t connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int islandPerimeter(vector<vector<int>>& A) {
int res = 0, dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
int n = A.size(), m = A[0].size();
for(int y = 0; y < n; y++) for(int x = 0; x < m; x++) {
if(!A[y][x]) continue;
res += 4;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and A[ny][nx]) res--;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/18/PS/LeetCode/island-perimeter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.