Zombie in Matrix

本文介绍了一个基于二维网格的僵尸扩散算法,通过广度优先搜索(BFS)策略,从所有僵尸位置开始,逐层向外扩散,直到所有人类被感染或无法继续扩散。文章详细解释了算法流程,包括如何处理墙壁障碍,以及如何判断最终状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a 2D grid, each cell is either a wall 2, a zombie 1 or people 0 (the number zero, one, two).Zombies can turn the nearest people(up/down/left/right) into zombies every day, but can not through wall. How long will it take to turn all people into zombies? Return -1 if can not turn all people into zombies.

Example

Example 1:

Input:
[[0,1,2,0,0],
 [1,0,0,2,1],
 [0,1,0,0,0]]
Output:
2

Example 2:

Input:
[[0,0,0],
 [0,0,0],
 [0,0,1]]
Output:
4

思路:所有的zombie 也就是grid[i][j] =1的点为一层,同时开始往外扩散;相当于一层一层的扩散;别忘记最后step空+1,要减去1

public class Solution {
    /**
     * @param grid: a 2D integer grid
     * @return: an integer
     */
    public int zombie(int[][] grid) {
        // BFS;
        if(grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int n = grid.length;
        int m = grid[0].length;
        boolean[][] visited = new boolean[n][m];
        Queue<int[]> queue = new LinkedList<int[]>();
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(grid[i][j] == 1) {
                    queue.offer(new int[]{i, j});
                }
            }
        }
        
        int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
        int step = 0;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                int[] node = queue.poll();
                visited[node[0]][node[1]] = true;
                
                for(int[] dir: dirs) {
                    int nx = node[0] + dir[0];
                    int ny = node[1] + dir[1];
                    if(0 <= nx && nx < n && 0 <= ny && ny < m 
                    && !visited[nx][ny] && grid[nx][ny] != 2 && grid[nx][ny] == 0) {
                        grid[nx][ny] = 1;
                        queue.offer(new int[]{nx, ny});
                    }
                }
            }
            step++;
        }
        
        boolean allone = true;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(grid[i][j] == 0) {
                    allone = false;
                }
            }
        }
        return allone == false ? -1 : step - 1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值