Description
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
Given a matrix:
0 1 2 0 0
1 0 0 2 1
0 1 0 0 0
return 2
5/13/2017
算法班,未经验证
注意,这里需要算需要多久,所以是层序遍历的问题,所以第39行开始是层序遍历的写法,普通BFS不需要,而且在放入queue之前就要先判断好是否是1,否则会无谓的监测一遍,day的最后值有出入
1 public class Solution { 2 /** 3 * @param grid a 2D integer grid 4 * @return an integer 5 */ 6 7 class Point{ 8 int x; 9 int y; 10 public Point(int x, int y) { 11 this.x = x; 12 this.y = y; 13 } 14 } 15 public int zombie(int[][] grid) { 16 17 // Write your code here 18 if (grid == null || grid.length == 0 || grid[0].length == 0) { 19 return -1; 20 } 21 int[] xDirection = new int[]{1, -1, 0, 0}; 22 int[] yDirection = new int[]{0, 0, 1, -1}; 23 24 // boolean[][] visited = new boolean[grid.length][grid[0].length]; 25 Queue<Point> queue = new LinkedList<Point>(); 26 int people = 0, day = 0; 27 28 for (int i = 0; i < grid.length; i++) { 29 for (int j = 0; j < grid[0].length; j++) { 30 if (grid[i][j] == 1) { 31 queue.offer(new Point(i, j)); 32 } else if (grid[i][j] == 0) { 33 people++; 34 } 35 } 36 } 37 38 while (!queue.isEmpty()) { 39 int size = queue.size(); 40 for (int i = 0; i < size; i++) { 41 Poing p = queue.poll(); 42 for (int j = 0; j < xDirection.length; i++) { 43 int tmpX = p.x + xDirection[j]; 44 int tmpY = p.y + yDirection[j]; 45 if (inBoundary(tmpX, tmpY, grid.length, grid[0].length) && grid[tmpX][tmpY] == 0) { 46 queue.offer(new Point(tmpX, tmpY)); 47 grid[tmpX][tmpY] = 1; 48 people--; 49 } 50 } 51 } 52 day++; 53 if (people == 0) { 54 return day; 55 } 56 } 57 return -1; 58 } 59 60 private boolean inBoundary(int x, int y, int xLength, int yLength) { 61 if (x < xLength && x >= 0 && y < yLength && y >= 0) return true; 62 return false; 63 } 64 65 }
时间: 2024-10-10 05:49:27