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); } }