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

点击上方“专知”关注获取更多AI知识!


关关的刷题日记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刷题)。 

 

专知网站查看Leetcode刷题日记:

请登录www.zhuanzhi.ai或者点击阅读原文,顶端搜索“Leetcode” 主题,取查看获得专知Leetcode所有资源!如下图所示~ 


群满,请扫描小助手,加入专知-LeetCode学习交流群,交流分享~


欢迎转发到你的微信群和朋友圈,分享专业AI知识!


获取更多关于机器学习以及人工智能知识资料,请访问www.zhuanzhi.ai,  或者点击阅读原文,即可得到!


-END-

欢迎使用专知

专知,一个新的认知方式!目前聚焦在人工智能领域为AI从业者提供专业可信的知识分发服务, 包括主题定制、主题链路、搜索发现等服务,帮你又好又快找到所需知识。


使用方法>>访问www.zhuanzhi.ai, 或点击文章下方“阅读原文”即可访问专知


中国科学院自动化研究所专知团队

@2017 专知


专 · 知


关注我们的公众号,获取最新关于专知以及人工智能的资讯、技术、算法、深度干货等内容。扫一扫下方关注我们的微信公众号。


点击“阅读原文”,使用专知

展开全文
Top
微信扫码咨询专知VIP会员