mycode 57.92%
class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ def recursive(i,j,row,col): if i>=0 and i<row and j>=0 and j<col: if grid[i][j] == '0': return grid[i][j] = '0' if i-1 >= 0: recursive(i-1,j,row,col) if i+1 < row: recursive(i+1,j,row,col) if j-1 >= 0: recursive(i,j-1,row,col) if j+1 <= col: recursive(i,j+1,row,col) else: return if not grid: return 0 row = len(grid) col = len(grid[0]) for i in range(row): for j in range(col): if grid[i][j] == '1': #print('if..',grid) recursive(i,j,row,col) grid[i][j] = '1' #print('if..',grid) count = 0 for i in range(row): for j in range(col): if grid[i][j] == '1': count += 1 return count
参考:
思路:其实第二次双层for循环是多余的,可以在前面就计数
class Solution: def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ res = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == "1": self.dfs(grid, r, c) res += 1 return res def dfs(self, grid, i, j): dirs = [[-1, 0], [0, 1], [0, -1], [1, 0]] grid[i][j] = "0" for dir in dirs: nr, nc = i + dir[0], j + dir[1] if nr >= 0 and nc >= 0 and nr < len(grid) and nc < len(grid[0]): if grid[nr][nc] == "1": self.dfs(grid, nr, nc)