深度优先遍历
注意grid 中的0, 1 均为字符串

class Solution:
    def dfs(self, grid, i, j, rows, cols):
        if i < 0 or j < 0 or j >= cols or i >= rows:
            return
        if grid[i][j] != '1':
            return
        grid[i][j] = '2'
        self.dfs(grid, i + 1, j, rows, cols)
        self.dfs(grid, i, j + 1, rows, cols)
        self.dfs(grid, i - 1, j, rows, cols)
        self.dfs(grid, i, j - 1, rows, cols)

    def solve(self, grid):
        # write code here
        if len(grid) < 1 or len(grid[0]) < 1:
            return 0
        rows = len(grid)
        cols = len(grid[0])
        ans = 0
        for i in range(rows):
            for j in range(cols):
                if grid[i][j] == '1':
                    self.dfs(grid, i, j, rows, cols)
                    ans += 1
        return ans