Python simple solution


  • 0
    P
    class Solution(object):
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            m, n = len(grid), len(grid[0])
            total = 0
            dup = 0
            for i in range(m):
            	for j in range(n):
            		if grid[i][j] == 1:
            			total += 1
            			for land in [ grid[x][y] for x,y in zip([i-1,i], [j,j-1]) if x>=0 and y>=0 ]:
            				if land == 1:
            					dup += 1
            res = 4*total - 2*dup
            return res
    

    and no improvements:

            m, n = len(grid), len(grid[0])
            total = 0
            dup = 0
            for i in range(m):
            	for j in range(n):
            		if grid[i][j] == 1:
            			total += 1
            			dup += sum([grid[x][y] for x,y in zip([i-1,i], [j,j-1]) if x>=0 and y>=0 ])
            res = 4*total - 2*dup
            return res
    

    Easy equation: perimneter = total_land * 4 - adjacent_lands_pair * 2


Log in to reply
 

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