LeetCode463. Island Perimeter(岛屿的周长)

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:

Input:
[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:

LeetCode463. Island Perimeter(岛屿的周长)_第1张图片


题目:岛屿的周长,且只有一个岛屿。

思路:https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution。在计算周长的时候,为什么需要减去两倍的相邻的1的数量,因为如果岛屿B在岛屿A的右侧,那么相当于AB的左侧,但是我们在循环的时候只计算了与岛屿相邻的右侧和下侧的情况,因此需要减去两倍。

工程代码下载

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int rows = grid.size();
        int cols = rows > 0 ? grid[0].size() : 0;
        if(cols == 0) return 0;

        int island_num = 0, neighbour_num = 0;
        for(int i = 0; i < rows; ++i){
            for(int j = 0; j < cols; ++j){
                if(grid[i][j] == 1){
                    ++island_num;
                    if(i+1 < rows && grid[i+1][j] == 1)
                        ++neighbour_num;
                    if(j+1 < cols && grid[i][j+1] == 1)
                        ++neighbour_num;
                }
            }
        }

        return 4*island_num - 2*neighbour_num;
    }
};

你可能感兴趣的:(leetcode)