Clear, Concise Python Solution


  • 0
    M
    class Solution(object):
        def inBounds(self, i, j):
            return 0 <= i < self.n and 0 <= j < self.m
        
        def searchSpot(self, grid, i, j):
            perimeter = 4
            dx = [-1, 0, 0, 1]
            dy = [ 0, 1,-1, 0]
            
            for x,y in zip(dx, dy):
                if self.inBounds(i + x, j + y):
                    perimeter -= grid[i + x][j + y]
    
            return perimeter
        
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            self.n, self.m = len(grid), len(grid[0])
            perimeter = 0
            for i in xrange(self.n):
                for j in xrange(self.m):
                    if grid[i][j] == 1:
                        perimeter += self.searchSpot(grid, i, j)
            return perimeter
    

Log in to reply
 

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