-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathislandPerimeter.cpp
More file actions
33 lines (32 loc) · 943 Bytes
/
islandPerimeter.cpp
File metadata and controls
33 lines (32 loc) · 943 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Source: https://leetcode.com/problems/island-perimeter/
// Author: Miao Zhang
// Date: 2021-02-14
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int res = 0;
int recnt = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j]) {
res++;
if (i > 0 && grid[i - 1][j]) {
recnt++;
}
if (j > 0 && grid[i][j - 1]) {
recnt++;
}
if (i + 1 < m && grid[i + 1][j]) {
recnt++;
}
if (j + 1 < n && grid[i][j + 1]) {
recnt++;
}
}
}
}
return res * 4 - recnt;
}
};