题目
Given a 2d grid map of '1'
s (land) and '0'
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
题意
给定一个由0,1组成的矩阵,1表示陆地,一个岛是由横竖相邻的1组成的。计算矩阵中岛屿的个数。
解题思路
遍历矩阵,对于每一个点(x,y)递归的查找(x + 1,y),(x - 1,y),(x,y + 1),(x,y - 1)是否为陆地。
代码
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
count = 0
col = len(grid)
if col == 0:
return count
row = len(grid[0])
for i in range(col):
for j in range(row):
if (grid[i][j] == '1'):
self.search(grid,i,j)
count += 1
return count
def search(self, grid, x, y):
"""
:type grid:List[List[str]]
:param grid:
:param x:
:param y:
"""
col = len(grid)
row = len(grid[0])
if x < 0 or x >= col or y < 0 or y >= row or grid[x][y] != '1':
return
grid[x][y] = '0'
self.search(grid,x + 1,y)
self.search(grid,x - 1,y)
self.search(grid,x,y + 1)
self.search(grid,x,y - 1)