Clear Readable Python Solution


  • 0
    M
    class Solution(object):
        def in_bounds(self,A,i,j,n,m,visited):
            return 0 <= i < n and 0 <= j < m and not visited[i][j] and A[i][j] is 1
        
        def DFS(self,A,i,j,n,m,visited):
            visited[i][j] = True
            
            dx = [-1, 0, 1, 0]
            dy = [ 0, 1, 0,-1]
            
            for x,y in zip(dx,dy):
                if self.in_bounds(A,i+x,j+y,n,m,visited):
                    self.DFS(A,i+x,j+y,n,m,visited)
            return 1
        
        def numIslands(self, grid):
            """
            :type grid: List[List[str]]
            :rtype: int
            """
            if not grid:
                return 0
            
            grid = [list(map(int,row)) for row in grid]
            n,m = len(grid), len(grid[0])
            visited = [[False for _ in xrange(m)] for _ in xrange(n)]
            count = 0
            for i in xrange(n):
                for j in xrange(m):
                    if not visited[i][j] and grid[i][j] is 1:
                        count += self.DFS(grid,i,j,n,m,visited)
            return count
            
    

Log in to reply
 

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