Python solution using BFS


  • 0
    H
    class Solution(object):
        def numIslands(self, grid):
            """
            :type grid: List[List[str]]
            :rtype: int
            """
            grid=list([[int(j) for j in i] for i in grid])
            q=[]
            if not grid:
                return 0
            m,n=len(grid),len(grid[0])
            count=0
            for i in xrange(m):
                for j in xrange(n):
                    if grid[i][j]!=1:
                        continue
                    count+=1
                    q.append((i,j))
                    grid[i][j]=2
                    while q:
                        x,y=q.pop(0)
                        if x and grid[x-1][y]==1:
                            q.append((x-1,y))
                            grid[x-1][y]=2
                        if y and grid[x][y-1]==1:
                            q.append((x,y-1))
                            grid[x][y-1]=2
                        if x+1<m and grid[x+1][y]==1:
                            q.append((x+1,y))
                            grid[x+1][y]=2
                        if y+1<n and grid[x][y+1]==1:
                            q.append((x,y+1))
                            grid[x][y+1]=2
            return count

Log in to reply
 

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