Zombie in Matrix

这里需要求具体多少步完成感染,所以我们不能只用单队列进行BFS了,因为这里的BFS是分层次的,所以再加如一个队列进行类似BFS二叉树那样的操作就行了

class Solution:
    """
    @param: grid: a 2D integer grid
    @return: an integer
    """
    def zombie(self, grid):
        # write your code here
        if not grid or not grid[0]:
            return -1

        n, m = len(grid), len(grid[0])
        queue = collections.deque([(i, j,) for i in xrange(n) for j in xrange(m) if grid[i][j] == 1])
        result = 0
        tmp = collections.deque([])
        while queue:
            row, col = queue.pop()
            for i, j in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
                curRow, curCol = row + i, col + j
                if 0 <= curRow < n and 0 <= curCol < m:
                    if not grid[curRow][curCol]:
                        grid[curRow][curCol] = 1
                        tmp.appendleft((curRow, curCol,))
            if not queue:
                queue = copy.copy(tmp)
                tmp.clear()
                result += 1

        check = sum([1 for i in xrange(n) for j in xrange(m) if grid[i][j] == 0])
        return result if check == 0 else -1

results matching ""

    No results matching ""