Python solution


  • 0
    A
    class Solution(object):
        def search_new_island(self, grid, r, c, R, C, visited):
            queue = [(r,c)]
            while len(queue)>0:
                pos = queue.pop()
                r = pos[0]
                c = pos[1]
                if not pos in visited:
                    visited.add(pos)
                    if c-1 >=0 and not (r, c-1) in visited and grid[r][c-1] == "1":
                        queue.append((r,c-1))
                    if r-1 >=0 and not (r-1, c) in visited and grid[r-1][c] == "1":
                        queue.append((r-1,c))
                    if c+1 < C and not (r, c+1) in visited and grid[r][c+1] == "1":
                        queue.append((r,c+1))
                    if r+1 < R and not (r+1, c) in visited and grid[r+1][c] == "1":
                        queue.append((r+1,c))
            
        def numIslands(self, grid):
            """
            :type grid: List[List[str]]
            :rtype: int
            """
            visited = set()
            num = 0
            R = len(grid)
            if R == 0:
                return 0
            C = len(grid[0])
            if C == 0:
                return 0
            for r in range(R):
                for c in range(C):
                    if not (r,c) in visited and grid[r][c] == "1":
                        num = num + 1
                        self.search_new_island(grid, r,c, R, C, visited)  
            return num
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.