From 74327b8c3bfaeb4a02a60fbfb08f2320d1312543 Mon Sep 17 00:00:00 2001 From: huangge1199 Date: Fri, 2 Jul 2021 16:06:53 +0800 Subject: [PATCH] =?UTF-8?q?LeetBook--=E9=98=9F=E5=88=97&=E6=A0=88--01=20?= =?UTF-8?q?=E7=9F=A9=E9=98=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leet/book/queueStack/UpdateMatrix.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/leet/book/queueStack/UpdateMatrix.java diff --git a/src/main/java/leet/book/queueStack/UpdateMatrix.java b/src/main/java/leet/book/queueStack/UpdateMatrix.java new file mode 100644 index 0000000..d8a57b4 --- /dev/null +++ b/src/main/java/leet/book/queueStack/UpdateMatrix.java @@ -0,0 +1,52 @@ +package leet.book.queueStack; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +/** + * Created with IntelliJ IDEA. + * + * @author: 轩辕龙儿 + * @date: 2021/7/2 15:49 + * @Description: No Description + */ +public class UpdateMatrix { + public static void main(String[] args) { + Solution solution = new UpdateMatrix().new Solution(); + } + + class Solution { + public int[][] updateMatrix(int[][] mat) { + Queue queue = new LinkedList<>(); + int xLength = mat.length; + int yLength = mat[0].length; + boolean[][] use = new boolean[xLength][yLength]; + for (int i = 0; i < xLength; i++) { + for (int j = 0; j < yLength; j++) { + if (mat[i][j] == 0) { + queue.offer(new int[]{i, j}); + use[i][j] = true; + } + } + } + int[][] ops = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + while (!queue.isEmpty()) { + int[] temp = queue.poll(); + int x = temp[0]; + int y = temp[1]; + for (int[] op : ops) { + int tx = x + op[0]; + int ty = y + op[1]; + if (tx >= 0 && tx < xLength && ty >= 0 && ty < yLength && !use[tx][ty]) { + mat[tx][ty] = mat[x][y] + 1; + queue.offer(new int[]{tx,ty}); + use[tx][ty]=true; + } + } + } + return mat; + } + } +}