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.

您将获得一个二维整数网格形式的地图,其中1代表土地,0代表水。

网格单元水平/垂直(不是对角线)连接。 网格完全被水包围,并且恰好有一个岛(即,一个或多个连接的陆地小区)。

岛上没有“湖泊”(里面的水与岛周围的水没有联系)。 一个单元格是边长为1的正方形。网格为矩形,宽度和高度不超过100.确定岛的周长。

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:

img

参考网上思路

pythons实战

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

class Solution(object):
    # 参考网上的思路,整个小岛的周长是4×陆地数-2×相交数
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        # 1. num找陆地数
        num = 0
        # 2. neg找相交数
        neg = 0
        M, N = len(grid), len(grid[0])
        # M:行数,N:列数
        for i in range(M):
            for j in range(N):
                if grid[i][j] == 1:
                    num += 1
                    if i < M - 1:
                        if grid[i+1][j] == 1:
                            neg += 1
                    if j < N - 1:
                        if grid[i][j+1] == 1:
                            neg += 1
        print(4*num-2*neg)
        return 4*num - 2*neg


if __name__ == '__main__':
    grid = [[0,1,0,0],
             [1,1,1,0],
             [0,1,0,0],
             [1,1,0,0]]
    Solution().islandPerimeter(grid)

参考网址:**

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦