Easy understand python solution


  • 0
    R

    Once we meet a cell which will contribute 4 to the final perimeter, however if it has a neighbor, the adjacent edge will not contribute to the perimeter, so we remove 1 from 4.

    class Solution(object):
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            
            result = 0
            if not grid:
                return result
            
            for row in range(len(grid)):
                for col in range(len(grid[0])):
                    if grid[row][col] == 1:
                        result= result+self.getPerimeter(row, col, grid)
            return result
        
        def getPerimeter(self, row, col, grid):
            
            perimeter = 4
            
            offsets = [(1, 0), (-1, 0), (0, 1), (0,-1)]
            for o in offsets:
                if 0<=row+o[0]<len(grid) and 0<=col+o[1]<len(grid[0]) and grid[row+o[0]][col+o[1]] == 1:
                    perimeter-=1
            
            return perimeter
            
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.