Breadth First Search
Posted jenna
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Breadth First Search相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode] Breadth-first Search
使用 Boost 的图 breadth_first_search() 在未加权、无向图中查找路径