1.问题描述
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.
Example:
[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 Explanation: The perimeter is the 16 yellow stripes in the image below:
2.算法分析
此问题可以转换为计算由单位正方形组成的不规则图形的周长问题。
1) 对于不相邻的n个正方形,毫无疑问它的周长为4*n;
2) 对于由n个单位正方形组成的不规则图形,总可以找到一个位于最上边的正方形i和一个位于最左边的正方形j
3)以i和j为基准,每多加一个正方形,周长加4,如果相邻,则再减去2;
4)对二维数组进行逐行和逐列遍历,从左上角开始,则所有的相邻情况都只有上相邻(i, j)和(i-1, j)以及左相邻(i, j)和(i,j-1)两种情况。
3.代码实现
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int res = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
//每次出现一个正方形,周长先加4,如果左边和上边都已有正方形,则周长均要减去2
if(grid[i][j] == 1){
res += 4;
if(i != 0 && grid[i-1][j] == 1)
res -= 2;
if(j != 0 && grid[i][j-1] == 1)
res -= 2;
}
}
}
return res;
}
};