Straightforward Python solution


  • 0
    R

    For every block of land, its perimeter is equal to 4 - # of land neighbors. Sum up all these values to get the total perimeter.

    def islandPerimeter(self, grid):
    	width = len(grid[0])
    	height = len(grid)
    	perimeter = 0
    
    	for y in range(height):
    	   for x in range(width):
    	       if grid[y][x] == 0:
    	           continue
    
    	   numOneNeighbors = int(y > 0 and grid[y-1][x] == 1) + int(x > 0 and grid[y][x-1] == 1) + int(y+ 1 < height and grid[y+1][x] == 1) + int(x + 1 < width and grid[y][x+1] == 1)
    	   perimeter += (4 - numOneNeighbors)
    
    	return perimeter
    

Log in to reply
 

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