DFS
class Solution(object):
def islandPerimeter(self,grid):
count = 0
def backtrack(count, x, y):
grid[x][y] = 2
for nx, ny in [(x - 1, y), (x + 1, y), (x, y + 1), (x, y - 1)]:
if not(0<=nx<len(grid) and 0<= ny < len(grid[0])): #邻居边界就+1
count += 1
if len(grid) > nx >= 0 and 0 <= ny < len(grid[0]) and grid[nx][ny]==0: #邻居是0就+1
count += 1
return count
xx = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
xx+=backtrack(count, i, j)
return xx
遍历从左到右,从上到下,相邻的就只要计算右边和下面就行不会重复
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
x1,x2 = 0,0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
x1 += 1
if i < len(grid)-1 and grid[i+1][j] == 1:
x2 += 1
if j < len(grid[0])-1 and grid[i][j+1] == 1:
x2 += 1
return 4*x1 - 2*x2