Python TLE...


  • 0
    C

    Time Limit Exceeded

    def num_islands(grid):
    
        if not grid:
            return 0
    
        island_tile = []
        res = 0
        # collect all island tile in a list
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == '1':
                    island_tile.append((i, j))
    
        # there is no island
        if not island_tile:
            return 0
    
        while island_tile:
            i, j = island_tile[0]
            dfs(island_tile, i, j)
            res += 1
        return res
    
    # mark neighbour tiles as visited
    def dfs(l, x, y):
        if (x, y) not in l:
            return
        l.remove((x, y))
        dfs(l, x+1, y)
        dfs(l, x-1, y)
        dfs(l, x, y+1)
        dfs(l, x, y-1)
    

Log in to reply
 

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