O(n*m) time O(1) space Simple PYTHON - very straightforward


  • 1
    V

    The if statements are very simplified. In this example, we are relying on short circuit evaluation on the or statements to guarantee that the cell exists in the grid before we check it.

    class Solution(object):
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            if not len(grid):
                return 0
            
            perimeter = 0
            for row in xrange(len(grid)):
                for col in xrange(len(grid[0])):
                    if not grid[row][col]:
                        continue
                    if row == 0 or not grid[row - 1][col]:
                        perimeter += 1
                    if row == len(grid) - 1 or not grid[row + 1][col]:
                        perimeter += 1
                    if col == 0 or not grid[row][col - 1]:
                        perimeter += 1
                    if col == len(grid[0]) - 1 or not grid[row][col + 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.