Zombie in Matrix
来源:互联网 发布:linux查看端口被占用 编辑:程序博客网 时间:2024/06/06 04:00
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.
Have you met this question in a real interview? Yes
Example
Given a matrix:
0 1 2 0 0
1 0 0 2 1
0 1 0 0 0
return 2
整体的解题思路还是使用bfs去处理,只是中间多了几个处理步骤而已。
没有bugfree,单词拼写是大问题。
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 */ int PEOPLE = 0; int WALL = 2; int ZOMBIE = 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 column = grid[0].length; int people = 0; int zombie = 0; Queue<Coordinate> queue = new LinkedList<>(); for(int i = 0; i < row; i++) { for(int j = 0; j < column; j++) { if (grid[i][j] == PEOPLE) { people++; } if (grid[i][j] == ZOMBIE) { zombie++; queue.offer(new Coordinate(i, j)); } } } if (people == 0) { return 0; } // bfs int[] directX = {0, 1, -1, 0}; int[] directY = {1, 0, 0, -1}; int day = 0; while (!queue.isEmpty()) { day++; int size = queue.size(); for (int a = 0; a < size; a++) { Coordinate node = queue.poll(); for (int i = 0; i < 4; i++) { Coordinate coor = new Coordinate(node.x + directX[i], node.y + directY[i]); if (!isPeople(grid, coor)) { continue; } if (grid[coor.x][coor.y] == PEOPLE) { grid[coor.x][coor.y] = ZOMBIE; people--; } if (people == 0) { return day; } queue.offer(coor); } } } return -1; } private boolean isPeople(int[][] grid, Coordinate coor) { int row = grid.length; int column = grid[0].length; if (coor.x < 0 || coor.x >= row) { return false; } if (coor.y < 0 || coor.y >= column) { return false; } if (grid[coor.x][coor.y] != PEOPLE) { return false; } return true; }}
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
- bootstrap-table 实现单击单元格可编辑
- 350. Intersection of Two Arrays II
- AngularJS动态切换样式
- JavaSE学习52:细说多线程之Thread类和Runable接口
- Servlet 单例吗?action单例吗?
- Zombie in Matrix
- yum info node报Error:No matching Packages to list yum没有对应的包信息。
- 针对无人机航拍视频中动态背景下的目标检测
- 1005. 继续(3n+1)猜想 (25)(java实现)
- JavaSE学习53:细说多线程之内存可见性
- 【C++学习】字符串分割
- 中间数
- Sheldon Numbers Gym
- cf Hard Process