Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1. Example 1:
Input:
0 0 0 0 1 0 0 0 0Output:
0 0 0 0 1 0 0 0 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1Output:
0 0 0 0 1 0 1 2 1
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
思路:BFS错不了,但是一个个点做的话会TLE,想想也是,不同的节点的BFS有一定的重叠,其实完全可以一起BFS遍历啊!
还有值得注意的一点是,给的输入是List,一般都是int[],所以这里就直接用输入,
package l542;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/*
* do bfs at same time
* 直接在输入的list对象上更改就好了
*/
public class Solution {
public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
Queue<int[]> q = new LinkedList<int[]>();
for(int i=0; i<matrix.size(); i++) {
for(int j=0; j<matrix.get(0).size(); j++) {
if(matrix.get(i).get(j) == 0) {
q.add(new int[]{i, j});
} else {
matrix.get(i).set(j, -1); //用来标识是否找到了该点的最短值
}
}
}
while(!q.isEmpty()) {
int[] cell = q.remove();
int x = cell[0], y = cell[1];
int step = matrix.get(x).get(y);
if(x > 0 && matrix.get(x-1).get(y) == -1) {
q.add(new int[]{x-1, y});
matrix.get(x-1).set(y, step+1);
}
if(y > 0 && matrix.get(x).get(y-1) == -1) {
q.add(new int[]{x, y-1});
matrix.get(x).set(y-1, step+1);
}
if(x < matrix.size()-1 && matrix.get(x+1).get(y) == -1) {
q.add(new int[]{x+1, y});
matrix.get(x+1).set(y, step+1);
}
if(y < matrix.get(0).size()-1 && matrix.get(x).get(y+1) == -1) {
q.add(new int[]{x, y+1});
matrix.get(x).set(y+1, step+1);
}
}
return matrix;
}
}