Simple Python O(m+n), space O(1) solution

  • 0

    If a cell and its neighbor are different, we got a edge. During the iteration, we look at the neighbors above it and to its left, and then add some other lines to take care of the corner cases (the first and the last rows and columns)

    def islandPerimeter(self, grid):
        m, n = len(grid), len(grid[0])
        def peri(i, j): 
            p = 0
            if i > 0: # left
                p += grid[i][j] != grid[i-1][j]
            if j > 0 : # up
                p += grid[i][j] != grid[i][j-1]
            if grid[i][j] == 1: # corner cases
                p += (i==0) + (i==m-1) + (j==0) + (j==n-1)
            return p
        return sum(peri(i,j) for i in xrange(m) for j in xrange(n))

Log in to reply

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