Simple, clean, recursive Python solution (beats 92%)


  • 0
    C
    class Solution(object):
        def numIslands(self, grid):
            """
            :type grid: List[List[str]]
            :rtype: int
            """
    
            counter = 0
            for i in xrange(len(grid)):
                for j in xrange(len(grid[i])):
                    if grid[i][j] == "1":
                        grid[i][j] = "0"
                        checkContiguous(grid, i, j)
                        counter += 1
            return counter
        
    def checkContiguous(matrix, row, col):
        #check to the right
        if col + 1 < len(matrix[row]):
            if matrix[row][col + 1] == "1":
                matrix[row][col + 1] = "0"
                checkContiguous(matrix, row, col + 1)
        #check below
        if row + 1 < len(matrix):
            if matrix[row + 1][col] == "1":
                matrix[row + 1][col] = "0"
                checkContiguous(matrix, row + 1, col)
        #check to the left
        if col > 0:
            if matrix[row][col - 1] == "1":
                matrix[row][col - 1] = "0"
                checkContiguous(matrix, row, col - 1)
        #check above
        if row > 0:
            if matrix[row - 1][col] == "1":
                matrix[row - 1][col] = "0"
                checkContiguous(matrix, row - 1, col)

  • 0
    L

    nice answer, but have some bugs such as self.checkContguous and def checkContiguous(self, matrix,row,col)


Log in to reply
 

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