Leetcode 542.01矩陣
阿新 • • 發佈:2019-02-14
== 處理 while pty 將他 cell mil upd 元素
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
註意:
- 給定矩陣的元素個數不超過 10000。
- 給定矩陣中至少有一個元素是 0。
- 矩陣中的元素只在四個方向上相鄰: 上、下、左、右。
思路
先把所有0入隊,把1置為MAX_VALUE,然後把最靠近0的1的距離算出來,然後將他們入隊,再算距離最靠近0的1的1的距離算出來,依次處理
1 importjava.util.LinkedList; 2 import java.util.List; 3 import java.util.Queue; 4 5 public class Solution { 6 public int[][] updateMatrix(int[][] matrix) { 7 int m = matrix.length; 8 int n = matrix[0].length; 9 10 Queue<int[]> queue = new LinkedList<>(); 11 for(int i = 0; i < m; i++) { 12 for (int j = 0; j < n; j++) { 13 if (matrix[i][j] == 0) { 14 queue.offer(new int[] {i, j}); 15 } 16 else { 17 matrix[i][j]=Integer.MAX_VALUE; 18 } 19 }20 } 21 22 int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 23 24 while (!queue.isEmpty()) { 25 int[] cell = queue.poll(); 26 for (int[] d : dirs) { 27 int r = cell[0] + d[0]; 28 int c = cell[1] + d[1]; 29 if (r < 0 || r >= m || c < 0 || c >= n || 30 matrix[r][c] <= matrix[cell[0]][cell[1]] + 1) continue; 31 queue.add(new int[] {r, c}); 32 matrix[r][c]=matrix[cell[0]][cell[1]] + 1; 33 } 34 } 35 36 return matrix; 37 } 38 }
Leetcode 542.01矩陣