python - island perimeter


  • 0
    S
    class Solution(object):
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            rows = len(grid)
            cols = len(grid[0])
            perimtr = 0
            
            for r in range(rows):
                for c in range(cols):
                    if grid[r][c]:
                        # top
                        if r == 0 or grid[r-1][c] == 0:
                            perimtr += 1
                        # down
                        if r == rows - 1 or grid[r+1][c] == 0:
                            perimtr += 1
                        # left
                        if c == 0 or grid[r][c-1] == 0:
                            perimtr += 1
                        # right
                        if c == cols - 1 or grid[r][c+1] == 0:
                            perimtr += 1
            
            return perimtr
    

Log in to reply
 

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