Clear Iterative Python Solution


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

Log in to reply
 

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