SUPER simple python, beats 90%


  • 0
    W
        def numIslands(self, grid):
            ans = 0
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    if grid[i][j] == '1':
                        ans += 1
                        self.sink(grid, j, i)
            return ans
        
        def sink(self, grid, x, y):
            if grid[y][x] == '1':
                grid[y][x] = '0'
            if x+1 < len(grid[y]) and grid[y][x+1] == '1':
                self.sink(grid, x+1, y)
            if x-1 >= 0 and grid[y][x-1] == '1':
                self.sink(grid, x-1, y)
            if y+1 < len(grid) and grid[y+1][x] == '1':
                self.sink(grid, x, y+1)
            if y-1 >= 0 and grid[y-1][x] == '1':
                self.sink(grid, x, y-1)
    

Log in to reply
 

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