Zombie in Matrix – Python 3 (Week 12 – 12)

  class Solution:
    """
    @param grid: a 2D integer grid
    @return: an integer
    """
    def zombie(self, grid):
        # write your code here
        
        if not grid or len(grid) == 0 or len(grid[0]) == 0:
            return 0
        
        ans = 0
        
        n, m = len(grid), len(grid[0])
        
        import queue
        qx = collections.deque()
        qy = collections.deque()
        dx = [0, 0, 1, -1]
        dy = [1, -1, 0, 0]
        
        for i in range(n):
            for j in range(m):
                if grid[i][j] == 1:
                    qx.append(i)
                    qy.append(j)
                    
        while qx:
            ans += 1
            size = len(qx)
            for i in range (size):
                cx = qx.popleft()
                cy = qy.popleft()
                print(cx)
                print(cy)
                for j in range(4):
                    nx = cx + dx[j]
                    ny = cy + dy[j]
                    if nx >= 0 and nx < n and ny >= 0 and ny < m and grid[nx][ny] == 0:
                        qx.append(nx)
                        qy.append(ny)
                        grid[nx][ny] = 1
                    
           
        for i in range(n):
            for j in range(m):
                if grid[i][j] == 0:
                    return -1
        
        return ans - 1

Time O(nm). Space O(mn).

Leave a comment

Design a site like this with WordPress.com
Get started