Number of Islands – Python 3 (Week 14 – 04)

 class Solution:
    """
    @param grid: a boolean 2D matrix
    @return: an integer
    """
    def numIslands(self, grid):
        # write your code here
        if not grid or not grid[0]:
            return 0
        
        islands = 0
        visited = set()
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] and (i, j) not in visited:
                    self.bfs(grid, i, j, visited)
                    islands += 1
        return islands            
                    
                    
                    
    
    def bfs(self, grid, x, y, visited):
        queue = collections.deque([(x, y)])
        visited.add((x, y))
        while queue:
            x, y = queue.popleft()
            for delta_x, delta_y in [(1, 0), (0, -1), (-1, 0), (0, 1)]:
                next_x = x + delta_x
                next_y = y + delta_y
                if not self.is_valid(grid, next_x, next_y, visited):
                    continue
                queue.append((next_x, next_y))
                visited.add((next_x, next_y))
    
    def is_valid(self,grid, next_x, next_y, visited):
        n, m = len(grid), len(grid[0])
        if not (0 <= next_x < n and 0 <= next_y < m):
            return False
        if (next_x, next_y) in visited:
            return False
        return grid[next_x][next_y]

Time, Space O(n). n is number of grids

Leave a comment

Design a site like this with WordPress.com
Get started