Island perimeter

Last updated

Last updated
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid:
return 0
rows = len(grid)
cols = len(grid[0])
default_cell_peri = 4
total_perimeter = 0
#print 'rows=', rows, 'cols=', cols
for r in xrange(rows):
for c in xrange(cols):
if grid[r][c] == 1:
cell_peri = default_cell_peri
#print 'r=', r, 'c=', c
# do inspection of e,w,n,s and decrement default_cell_peri
if r-1 >=0 and grid[r-1][c] == 1: # land in North
cell_peri -= 1
if r+1 <= (rows-1) and grid[r+1][c] == 1: # land in South
cell_peri -= 1
if c-1 >= 0 and grid[r][c-1] == 1: # land in West
cell_peri -= 1
if c+1 <= (cols-1) and grid[r][c+1] == 1: # land in East
cell_peri -= 1
total_perimeter += cell_peri
return total_perimeter