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