You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The 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" (water inside that 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.
解法:
每个身为land的方格只用考虑它左边和上边有没有land,如果有,边长-2。
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int width = grid[0].size();
int height = grid.size();
int count = 0;
int sub=0;
for (int i=0; i<height; i++){
for (int j=0; j<width; j++){
if (grid[i][j]==1){
count += 4;
if (j != 0){
sub += left(i, j, grid);
}
if (i != 0) {
sub += up(i, j, grid);
}
}
}
}
return count-sub;
}
int left(int i, int j, vector<vector<int>>& grid){
if (grid[i][j-1]){
return 2;
}
return 0;
}
int up(int i, int j, vector<vector<int>>& grid){
if (grid[i-1][j]){
return 2;
}
return 0;
}
};