200. Number of Islands (Medium) - TengnanYao/daily_leetcode GitHub Wiki

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        def dfs(i, j):
            seen.add((i, j))
            for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                x, y = i + dx, j + dy
                if 0 <= x < m and 0 <= y < n and (x, y) not in seen:
                    if grid[x][y] == "1":
                        dfs(x, y)
        seen = set()
        m, n = len(grid), len(grid[0])
        result = 0
        for i in range(m):
            for j in range(n):
                if (i, j) not in seen and grid[i][j] == "1":
                    dfs(i, j)
                    result += 1
        return result