1. 程式人生 > >【LeetCode】463. Island Perimeter 解題報告(Python)

【LeetCode】463. Island Perimeter 解題報告(Python)

作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/


目錄

題目地址:https://leetcode.com/problems/island-perimeter/description/

題目描述

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:

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:

此處輸入圖片的描述

題目大意

給了一個二維陣列表示的一張地圖,如果某個位置是1,那麼表示的是陸地,位置是0表示的是海洋。已知陸地連在一起的話會構成一個小島,而且這個地圖裡面只有一個小島。求小島的周長。

解題方法

減去相交部分

直接求解好像很難,可以使用一個簡單的方法:每個位置的周長是4,如果和另一個陸地相連,那麼這兩個陸地周長和減去2.所以整個小島的周長是4×陸地數-2×相交數。

class Solution:
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        M, N = len(grid), len(grid[0])
        counts = 0
        neighbors = 0
        for i in range(M):
            for j in range(N):
                if grid[i][j] == 1:
                    counts += 1
                    if i < M - 1:
                        if grid[i + 1][j] == 1:
                            neighbors += 1
                    if j < N - 1:
                        if grid[i][j + 1] == 1:
                            neighbors += 1
        return 4 * counts - 2 * neighbors

參考資料

https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution

日期

2018 年 11 月 8 日 —— 專案進展緩慢