463. Island Perimeter
https://leetcode.com/problems/island-perimeter/description/
[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16
Thoughts
Code
/*
* @lc app=leetcode id=463 lang=cpp
*
* [463] Island Perimeter
*/
// @lc code=start
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
const int M = grid.size(), N = M == 0 ? 0 : grid[0].size();
int res = 0;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (grid[i][j] == 0) continue;
res += 4;
if (i < M - 1 && grid[i + 1][j] == 1) res -= 2;
if (j < N - 1 && grid[i][j + 1] == 1) res -= 2;
}
}
return res;
}
};
// @lc code=end
Analysis
Last updated