题解 | #岛屿数量#
岛屿数量
http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
判断岛屿数量
@param grid char字符型二维数组
@return int整型
class Solution: def solve(self , grid: List[List[str]]) -> int: # write code here row = len(grid) col = len(grid[0]) res = 0 if row == 0 or col == 0: return 0 def dfs(x,y): grid[x][y] = '0' for c in [[1,0], [-1,0], [0,1], [0,-1]]: nx = x + c[0] ny = y + c[1] if 0<=nx<row and 0<=ny<col and grid[nx][ny] == '1': dfs(nx,ny)
for i in range(row):
for j in range(col):
if grid[i][j] == '1':
dfs(i,j)
res += 1
return res