10 line DFS python


  • 0
    Y
        def numIslands(self, grid):
            if not grid: return 0
            sft = [0, 1, 0, -1, 0]
            def paint(x, y):
                if  0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] == '1':
                    grid[x][y] = '0'
                    for i in xrange(4):
                        paint(x + sft[i], y + sft[i + 1])
                    return 1
                return 0
            return sum([paint(x, y) for x in xrange(len(grid)) for y in xrange(len(grid[0]))])
    

Log in to reply
 

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