码迷,mamicode.com
首页 > 其他好文 > 详细

Breadth First Search

时间:2019-05-23 10:53:05      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:else   mat   esc   people   integer   ++   nbsp   read   rom   

598. Zombie in Matrix

https://www.lintcode.com/problem/zombie-in-matrix/description?_from=ladder&&fromId=1

class Coordinate {
    int x, y;
    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Solution {
    /**
     * @param grid: a 2D integer grid
     * @return: an integer
     */
    public int PEOPLE = 0;
    public int ZOMBIE =  1;
    public int WALL = 2;
    
    public int[] deltaX = {1, 0, -1, 0};
    public int[] deltaY = {0, 1, 0, -1};
    
    public int zombie(int[][] grid) {
        // write your code here
        if(grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int row = grid.length;
        int col = grid[0].length;
        Queue<Coordinate> queue = new LinkedList<>();
        int people = 0;
        
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(grid[i][j] == PEOPLE) {
                    people++;
                } else if(grid[i][j] == ZOMBIE) {
                    queue.offer(new Coordinate(i, j));
                }
            }
        }
        
        //corner case
        if(people == 0) {
            return 0;
        }
        
        int days = 0;
        while(!queue.isEmpty()) {
            days++;
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                Coordinate zb = queue.poll();
                for(int direction  = 0; direction < 4; direction++) {
                    Coordinate adj = new Coordinate(
                      zb.x + deltaX[direction],  
                      zb.y + deltaY[direction]
                    );
                    if(!isPeople(adj, grid)) {
                        continue;
                    }
                    people--;
                    grid[adj.x][adj.y] = ZOMBIE;
                    if(people == 0) {
                        return days;
                    }
                    queue.offer(adj);
                }
            }
        }
        return -1;
    }
    
    public boolean isPeople(Coordinate adj, int[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        if(adj.x < 0 || adj.x >= row) {
            return false;
        }
        if(adj.y < 0 || adj.y >= col) {
            return false;
        }
        return grid[adj.x][adj.y] == PEOPLE;
    }
}

 

Breadth First Search

标签:else   mat   esc   people   integer   ++   nbsp   read   rom   

原文地址:https://www.cnblogs.com/jenna/p/10910520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!