LintCode 433. 岛屿的个数(Number of Islands)
代码:
class Solution:
"""
@param grid: a boolean 2D matrix
@return: an integer
"""
def numIslands(self, grid):
# write your code here
n_Islands=0
n_rows=len(grid)
if n_rows:
n_cols=len(grid[0])
for i in range(n_rows):
for j in range(n_cols):
if grid[i][j]==-1 or grid[i][j]==0:
continue
else:
self.Islands(grid,i,j,n_rows,n_cols)
n_Islands+=1
return n_Islands
def Islands(self,grid,i,j,n_rows,n_cols):
if i<0 or j<0 or i>n_rows-1 or j>n_cols-1:
return
elif grid[i][j]==-1 or grid[i][j]==0:
return
elif grid[i][j]==1:
grid[i][j]=-1
self.Islands(grid,i-1,j,n_rows,n_cols)
self.Islands(grid,i+1,j,n_rows,n_cols)
self.Islands(grid,i,j+1,n_rows,n_cols)
self.Islands(grid,i,j-1,n_rows,n_cols)
return