【LeetCode 463】 关关的刷题日记29 Island Perimeter

时间:2022-05-07
本文章向大家介绍【LeetCode 463】 关关的刷题日记29 Island Perimeter,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记29 – Leetcode 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.

[[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:

题目的意思是:有一个二维数组里面只有0和1,1表示土地,0表示水。土地被水环绕着,并且里面没有湖,也就是说1是连成一片的,里面没有0,让我们求土地的周长。

思路

思路:我们先用网格数*4算出所有网格的边长和,然后再减去在土地中间的边长。为了避免重复计算,我们只看每个1的左边和上边有没有1与它相连,如果有的话,总体的周长要减去2.

class Solution {public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int count=0, repeat=0;
        for(int i=0; i<grid.size(); i++)
        {
            for(int j=0; j<grid[i].size(); j++)
            {
                if(!grid[i][j])
                    continue;
                count++;
                if(i!=0 && grid[i-1][j]==1)
                    repeat++;
                if(j!=0 && grid[i][j-1]==1)
                    repeat++;
            }
        }
        return 4*count-2*repeat;
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang,注明Leetcode刷题)。