463. Island Perimeter

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:
463. Island Perimeter_第1张图片
image

思路:先数有几个land(棕色),不考虑重复边的话,总边数=land4.
然而有重复边,即相邻两个land的公共边被重复计算了两次,记总的重复边为repeat,则最终结果为land
4-repeat*2

class Solution {
public:
    int islandPerimeter(vector>& grid) {
        int count = 0; // land计数
        int repeat = 0; // 重复边计数
        int row = grid.size();
        int col = grid[0].size();
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 1) {
                    count++; // land计数+1
                    // 若找到一个land,检查其右边和下方的区域是否也为land,若是,则重复边+1
                    // 注意i和j不要越界
                    if (j != row-1 && grid[i][j+1] == 1) repeat++;
                    if (i != col-1 && grid[i+1][j] == 1) repeat++;
                }
            }
        }
        return count*4 - repeat*2;
    }
};

你可能感兴趣的