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

Example:

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

Easy

方法

對(duì)于一個(gè)island,如果它有n個(gè)相鄰的island,那它提供的周長(zhǎng)為4-n,將每個(gè)island提供的周長(zhǎng)相加即可

python代碼
class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        perimeter = 0
        gridRows = len(grid)
        if gridRows == 0:
            return 0
        gridCols = len(grid[0])
        for i in range(gridRows):
            for j in range(gridCols):
                if grid[i][j] == 1:
                    perimeter += 4
                    if i > 0 and grid[i-1][j]:
                        perimeter -= 1
                    if j > 0 and grid[i][j-1]:
                        perimeter -= 1
                    if i+1 < gridRows and grid[i+1][j]:
                        perimeter -= 1
                    if j+1 < gridCols and grid[i][j+1]:
                        perimeter -= 1

        return perimeter

assert Solution().islandPerimeter([[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]) == 16
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容