๐ฎ542 01 Matrix
https://leetcode.com/problems/01-matrix/
่ถ ็บงๅฎนๆtle๏ผ้่ฟ็ๆนๆณๆฏไป0่ไธๆฏ1ๅผๅงbfs๏ผๅๆถไธ่ฆ้ๅฐไธไธชๅฐฑbfsไธๆฌก๏ผๆๆๆ0็ไฝ็ฝฎ้ฝๅ ่ฟๅปๅbfs๏ผbfs็่ฟ็จไธญๆดๆฐans
ideaๆฏๅจ็ฌฌไธ่ฝฎๅฐฑๆพๅฐๆๆๅ0็ดๆฅๆฅ่งฆ็1๏ผๆดๆฐๅฎไปฌ็่ท็ฆป๏ผไนๅฐฑๆฏ1๏ผ๏ผ็ถๅqueue้ๆฅไธๆฅๅฉไธ็ๅฐฑๆฏไธๅฑไธๅฑๅ0้ดๆฅๆฅ่งฆ็1ไบ
class Solution {
public int[][] DIR = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
private class Node {
int i;
int j;
public Node(int i, int j) {
this.i = i;
this.j = j;
}
public String toString() {
return i + " " + j;
}
}
public int[][] updateMatrix(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
ans[i][j] = Integer.MAX_VALUE;
}
}
}
Queue<Node> queue = new ArrayDeque<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
continue;
}
queue.offer(new Node(i, j));
}
}
bfs(mat, ans, queue);
return ans;
}
private void bfs(int[][] mat, int[][] ans, Queue<Node> queue) {
Set<String> visited = new HashSet<>();
int len = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int s = 0; s < size; s++) {
Node node = queue.poll();
// System.out.println(node.toString());
if (visited.contains(node.toString())) {
continue;
}
visited.add(node.toString());
if (mat[node.i][node.j] == 1) {
// System.out.println(ans[node.i][node.j]);
ans[node.i][node.j] = Math.min(ans[node.i][node.j], len);
}
for (int[] dir : DIR) {
int x = node.i + dir[0];
int y = node.j + dir[1];
if (x >= 0 && x < mat.length && y >= 0 && y < mat[0].length) {
queue.offer(new Node(x, y));
}
}
}
len++;
}
}
}
Last updated