Easy to read and understand Python solution


  • 0
    N

    Very easy 2-forloop solution for anybody who wants to do it the simple way.
    My strategy here is to go grid by grid and see if it is an edge grid (top, bottom, left or right).
    If not, we can safely go and grab adjacent grid value and see if we have a perimeter (if adjacent block's value is 0).

    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        perimeter = 0
        for i, row in enumerate(grid):
            for j, col in enumerate(row):
                if col == 1:
                    #top
                    if i == 0:
                        perimeter +=1
                    else:
                        if grid[i-1][j] == 0:
                            perimeter +=1
                    #bottom
                    if i == len(grid)-1:
                        perimeter +=1
                    else:
                        if grid[i+1][j] == 0:
                            perimeter +=1
                    #left    
                    if j == 0:
                        perimeter +=1
                    else:
                        if row[j-1] == 0:
                            perimeter +=1
                    #right
                    if j == len(row)-1:
                        perimeter +=1
                    else:
                        if row[j+1] == 0:
                            perimeter +=1
                        
        return perimeter

Log in to reply
 

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