代码拉取完成,页面将自动刷新
package com.hit.basmath.learn.queue_stack;
import java.util.LinkedList;
import java.util.Queue;
/**
* 542. 01 Matrix
* <p>
* Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
* <p>
* The distance between two adjacent cells is 1.
* <p>
* Example 1:
* <p>
* Input:
* <p>
* [[0,0,0],
* [0,1,0],
* [0,0,0]]
* <p>
* Output:
* <p>
* [[0,0,0],
* [0,1,0],
* [0,0,0]]
* <p>
* Example 2:
* <p>
* Input:
* <p>
* [[0,0,0],
* [0,1,0],
* [1,1,1]]
* <p>
* Output:
* <p>
* [[0,0,0],
* [0,1,0],
* [1,2,1]]
* <p>
* Note:
* <p>
* 1. The number of elements of the given matrix will not exceed 10,000.
* 2. There are at least one 0 in the given matrix.
* 3. The cells are adjacent in only four directions: up, down, left and right.
*/
public class _542 {
public int[][] updateMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
queue.offer(new int[]{i, j});
} else {
matrix[i][j] = Integer.MAX_VALUE;
}
}
}
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!queue.isEmpty()) {
int[] cell = queue.poll();
for (int[] d : dirs) {
int r = cell[0] + d[0];
int c = cell[1] + d[1];
if (r < 0 || r >= m || c < 0 || c >= n ||
matrix[r][c] <= matrix[cell[0]][cell[1]] + 1) continue;
queue.add(new int[]{r, c});
matrix[r][c] = matrix[cell[0]][cell[1]] + 1;
}
}
return matrix;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。