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:

 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]
Answer: 16Explanation: The perimeter is the 16 yellow stripes 

想了下,其实就是每个块都是四个边,然后减去上下左右重复的一个边就可以了:

    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        if not grid:
            return 0
        cnt = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    cnt += 4
                    if (i > 0 and grid[i-1][j] == 1):
                        cnt -=1
                    if (j > 0 and grid[i][j-1] == 1):
                        cnt -=1
                    if (i<len(grid)-1 and grid[i+1][j] == 1):
                        cnt -=1
                    if (j<len(grid[0])-1 and grid[i][j+1] == 1):
                        cnt -=1
        
        return cnt
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,896评论 0赞 23
  • 人生四十二件赏心乐事 人生四十二件赏心乐事,高卧、静坐、尝酒、试茶、阅书、临帖、 对画、诵经、咏歌、鼓琴、焚香、莳...
    xcy无名阅读 1,609评论 0赞 1
  • 酉丁春暮小苏杭, 人寄篱檐视水塘。 几何人间事最美? 最美四月金川香。
    0尼阅读 204评论 0赞 1
  • 今天的生活过得普普通通,没有波澜。准确地说,是与床为伴,手机不离身,典型的宅生活。 今天任然有许多需要做的事情,但...
    非宁静无以致远_渊宁阅读 126评论 0赞 1

友情链接更多精彩内容