版权声明:转载请和我说。 https://blog.csdn.net/u010929628/article/details/89737827
题目内容
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:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
题目思路
对于一个岛屿来说,上下左右联通的1构成了他们。所以我们只要探索一个岛屿,沉没一个岛屿就可以了。
程序代码
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
m=len(grid)
if m==0:
return 0
n=len(grid[0])
if n==0:
return 0
newGrid=[[0]*(n+2) for i in range(m+2)]
for i in range(1,m+1):
for j in range(1,n+1):
newGrid[i][j]=int(grid[i-1][j-1])
def clear(i,j):
if newGrid[i][j]==0:
return
newGrid[i][j]=0
clear(i+1,j)
clear(i-1,j)
clear(i,j+1)
clear(i,j-1)
return
count=0
for i in range(1,m+1):
for j in range(1,n+1):
if newGrid[i][j]==1:
count+=1
clear(i,j)
return count