My DFS solution in Python


  • -1
    L
    class Solution:
        # @param {character[][]} grid
        # @return {integer}
        def numIslands(self, grid):
            if len(grid) == 0:
                return 0
            nrow = len(grid)
            ncol = len(grid[0])
            counter = 0
            for row in range(nrow):
                for col in range(ncol):
                    if grid[row][col] == '1':
                        counter = counter + 1
                        DFS(row,col,nrow,ncol,grid)
            return counter
    def DFS(row,col,nrow,ncol,grid):
        grid[row][col] = '0'
        if row!=0 and grid[row-1][col] == '1':
            DFS(row-1,col,nrow,ncol,grid)
        if row!=nrow-1 and grid[row+1][col] == '1':
            DFS(row+1,col,nrow,ncol,grid)
        if col!=0 and grid[row][col-1]=='1':
            DFS(row,col-1,nrow,ncol,grid)
        if col!=ncol-1 and grid[row][col+1]=='1':
            DFS(row,col+1,nrow,ncol,grid)

Log in to reply
 

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