A Very Straightforward Python Solution


  • 0
    E

    Well, the idea is quite simple, iterate all squares and look around for neighbors:

    class Solution(object):
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            rtn = 0
            
            for row_id, row_value in enumerate(grid):
                for column_id, column_value in enumerate(row_value):
                    if column_value == 1:
                        if (column_id - 1) < 0 or row_value[column_id - 1] == 0:
                            # left
                            rtn += 1
    
                        if (row_id - 1) < 0 or grid[row_id - 1][column_id] == 0:
                            # top
                            rtn += 1
    
                        if (column_id + 1) >= len(row_value) or row_value[column_id + 1] == 0:
                            # right
                            rtn += 1
    
                        if (row_id + 1) >= len(grid) or grid[row_id + 1][column_id] == 0:
                            # bottom
                            rtn += 1
    
            return rtn
    

Log in to reply
 

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