Python straightforward solution with two for loops


  • 0
    G

    Go through element one by one and count how many edges to add based on whether its right and up neighbors are 1.

    class Solution(object):
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            dim_1, dim_2 = len(grid), len(grid[0])
            #first cell 
            cnt = 4 if grid[0][0] else 0
            #first row
            for j in range(1, dim_2):
                if grid[0][j]:
                    cnt += 2 if grid[0][j-1] else 4
            #remaining rows
            for i in range(1, dim_1):
                #first cell
                if grid[i][0]:
                    cnt += 2 if grid[i-1][0] else 4
                for j in range(1, dim_2):
                    if grid[i][j]:
                        #right = 1
                        if grid[i][j-1]:
                            cnt += 0 if grid[i-1][j] else 2 
                        # right = 0
                        else:
                            cnt += 2 if grid[i-1][j] else 4
            return cnt
    

Log in to reply
 

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