Zombie in Matrix
来源:互联网 发布:公积金贷款的软件 编辑:程序博客网 时间:2024/06/05 00:30
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.
class Coordinate { int x; int 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 zombie(int[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == 0) { return -1; } int n = grid.length; int m = grid[0].length; int people = 0; Queue<Coordinate> queue = new LinkedList<>(); int[] directionX = {0, 0, 1, -1}; int[] directionY = {1, -1, 0, 0}; //找到所有僵尸,统计所有人数 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { queue.offer(new Coordinate(i, j)); } if (grid[i][j] == 0) { people++; } } } if (people == 0) { return 0; } int time = 0; while (!queue.isEmpty()) { int size = queue.size(); time++; //System.out.println("当前是第" + time + "天,还剩" + people + "人"); for (int i = 0; i < size; i++) { //分层遍历,增加一层for循环,在for循环里再进行poll()!!! Coordinate coor = queue.poll(); for (int j = 0; j < 4; j++) { Coordinate adj = new Coordinate( coor.x + directionX[j], coor.y + directionY[j] ); if (inBound(adj, grid)) { if (grid[adj.x][adj.y] == 0) { grid[adj.x][adj.y] = 1; people--; if (people == 0) { return time; } queue.offer(adj); } } } } } return -1; } private boolean inBound(Coordinate coor, int[][] grid) { int n = grid.length; int m = grid[0].length; int x = coor.x; int y = coor.y; return x >= 0 && x < n && y >= 0 && y < m && grid[x][y] != 2; }}
0 0
- Zombie in Matrix
- Zombie in Matrix
- Zombie in Matrix
- zombie
- How To Catch The Memory Zombie In Xcode
- zombie and orphan process in Linux-Unix systems
- Killing zombie process & emacs Copy paste in putty
- Matrix structure in XNA
- view Matrix in opengl
- Matrix multiplication in OpenCV
- CCI: Find in Matrix
- Matrix In OpenGL
- matrix inversion in boost
- B. OR in Matrix
- B. OR in Matrix
- B. OR in Matrix
- 【COderForces】OR in Matrix
- Missing number in matrix
- 常用命令http://blog.csdn.net/hsd2012/article/details/51074806
- java的运行
- Codeforces 776C-Molly's Chemicals
- 中学生应具备的良好的学习习惯
- LeetCode : Base 7
- Zombie in Matrix
- 实现工作汇报
- UDT协议学习笔记(一)UDT概述
- 在VS2015中安装opencv的步骤
- Spring Boot的三种启动方式
- PAT A1013. Battle Over Cities (25)
- RCNN系列学习笔记(1):Rich feature hierarchies for accurate object detection and semantic segmentation
- 尚观嵌入式c语言编程进阶笔记——3.指针
- 构造函数与析构函数