package array.medium;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
/**
* @Auther: xiaof
* @Date: 2020/4/15 10:49
* @Description: 542. 01 矩阵
* 给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
* 两个相邻元素间的距离为 1 。
* 示例 1:
* 输入:
*
* 0 0 0
* 0 1 0
* 0 0 0
* 输出:
*
* 0 0 0
* 0 1 0
* 0 0 0
* 示例 2:
* 输入:
*
* 0 0 0
* 0 1 0
* 1 1 1
* 输出:
*
* 0 0 0
* 0 1 0
* 1 2 1
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/01-matrix
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class UpdateMatrix {
/**
*
* 功能描述:
* 执行用时 : 24 ms , 在所有 Java 提交中击败了 39.08% 的用户
* 内存消耗 : 41.8 MB , 在所有 Java 提交中击败了 100.00% 的用户
*https://leetcode-cn.com/problems/01-matrix/solution/01ju-zhen-by-leetcode-solution/
* @author: xiaof
* @date: 2020/4/15 11:37
* @Description:
*/
int[] dirx = {-1, 1, 0, 0}, diry = {0, 0, -1, 1};
public int[][] solution(int[][] matrix) {
//判断所有位置
int mxl = matrix.length, myl = matrix[0].length;
int[][] res = new int[mxl][myl];
int[][] hadfind = new int[mxl][myl];
//查询搜索
Queue queue = new ArrayDeque();
//获取所有的0
for (int i = 0; i < mxl; ++i) {
for (int j = 0; j < myl; ++j) {
if (matrix[i][j] == 0) {
queue.offer(new int[]{i, j});
hadfind[i][j] = 1; //标识已经被遍历过
}
}
}
//围绕所有的0,进行广度遍历,0本身距离是0,往外就是+1
while (!queue.isEmpty()) {
int[] tmp = (int[]) queue.poll();
//4个方向判断
for (int i = 0; i < 4; ++i) {
int nx = tmp[0] + dirx[i], ny = tmp[1] + diry[i];
//判断在范围内
if (nx >= 0 && nx < mxl && ny >= 0 && ny < myl && hadfind[nx][ny] != 1) {
//设置新值
res[nx][ny] = res[tmp[0]][tmp[1]] + 1; //原来的位置递增1个距离
hadfind[nx][ny] = 1;
//吧新位置加入队列
queue.offer(new int[]{nx, ny});
}
}
}
return res;
}
public static void main(String[] args) {
UpdateMatrix fuc = new UpdateMatrix();
int[][] matrix1 = new int[][]{{0,0,0,},{0,1,0},{1,1,1}};
fuc.solution(matrix1);
}
}