A naive python solution


  • 0
    S
    class Solution(object):
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """       
            result = 0
            for i in xrange(len(grid)):
                for j in xrange(len(grid[i])):
                    if grid[i][j] == 1:
                        contribute = 4
                        if i+1<len(grid) and grid[i+1][j] == 1:
                            contribute -= 1
                        if i-1>=0 and grid[i-1][j] == 1:
                            contribute -= 1
                        if j-1>=0 and grid[i][j-1] == 1:
                            contribute -= 1
                        if j+1<len(grid[i]) and grid[i][j+1] == 1:
                            contribute -= 1
                        result += contribute
            return result

Log in to reply
 

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