Description:
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.
这道题只要遍历一遍矩阵,找到属于岛的cell,然后检查它上下左右相邻的cell是否也属于岛。记录所有属于岛的cell的数目num
和岛上所有相邻的边的数目edge
。最后岛的周长就可以由公式num * 4 - edge
得到:
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int edge = 0;
int num = 0;
for (int i=0; i<grid.size(); i++) {
for (int j=0; j<grid[i].size(); j++) {
if (grid[i][j]) {
num++;
if (i > 0) edge += grid[i-1][j];
if (i < grid.size()-1) edge += grid[i+1][j];
if (j > 0) edge += grid[i][j-1];
if (j < grid[i].size()-1) edge += grid[i][j+1];
}
}
}
return num * 4 - edge;
}
};