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 

想了下,其實(shí)就是每個(gè)塊都是四個(gè)邊,然后減去上下左右重復(fù)的一個(gè)邊就可以了:

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

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

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,899評(píng)論 0 23
  • 人生四十二件賞心樂事 人生四十二件賞心樂事,高臥、靜坐、嘗酒、試茶、閱書、臨帖、 對(duì)畫、誦經(jīng)、詠歌、鼓琴、焚香、蒔...
    xcy無名閱讀 1,472評(píng)論 0 1
  • 酉丁春暮小蘇杭, 人寄籬檐視水塘。 幾何人間事最美? 最美四月金川香。
    0尼閱讀 174評(píng)論 0 1
  • 今天的生活過得普普通通,沒有波瀾。準(zhǔn)確地說,是與床為伴,手機(jī)不離身,典型的宅生活。 今天任然有許多需要做的事情,但...
    非寧靜無以致遠(yuǎn)_淵寧閱讀 98評(píng)論 0 1