This easy question gives a skeleton for iterating a matrix and checking for boundary conditions.
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
nrows = len(grid)
ncols = len(grid[0])
counts = 0
for i in range(nrows):
for j in range(ncols):
if grid[i][j] == 1:
if i-1<0:
counts += 1
else:
if grid[i-1][j] == 0:
counts += 1
if i+1>=nrows:
counts += 1
else:
if grid[i+1][j] == 0:
counts += 1
if j-1<0:
counts += 1
else:
if grid[i][j-1] == 0:
counts += 1
if j+1>=ncols:
counts += 1
else:
if grid[i][j+1] == 0:
counts += 1
return counts
No comments:
Post a Comment