给一个01矩阵,求不同的岛屿的个数。
0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻
思路: 遇到1时 搜索1的上下左右是否有1 有的话,将1置0。(搜素不要超出范围)
class Solution:
# @param {boolean[][]} grid a boolean 2D matrix
# @return {int} an integer
def numIslands(self, grid):
# Write your code here
count = 0
m = len(grid)
n = len(grid[0])
if m == 0 or n == 0:
return 0
for i in range(m):
for j in range(n):
if grid[i][j]:
self.dfs(grid, i, j)
count += 1
return count
def dfs(self, grid, i, j):
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]):
return
if grid[i][j] == 1:
grid[i][j] = 0
self.dfs(grid, i-1, j)
self.dfs(grid, i+1, j)
self.dfs(grid, i, j-1)
self.dfs(grid, i, j+1)