问题定义
给定一个由 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。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。、
解决思路
看了题目,第一眼上来,觉得不就是广度优先搜索寻找每个1到0的最短路径,结果就入坑了,因为从每个1开始寻找0,每次都会搜索四次,从而导致时间复杂度飙升。结果自然就是没法AC:
class Solution {
public int[][] updateMatrix(int[][] matrix) {
int row = matrix.length;
int column = matrix[0].length;
for(int i =0;i<row;i++){
for(int j =0;j<column;j++){
int dist = 0;
if(matrix[i][j]!=0){
boolean[][] visited = new boolean[row][column];
Queue<int[]> queue = new LinkedList();
visited[i][j] = true;
int []vector= new int[]{i,j};
queue.add(vector);
l:while(!queue.isEmpty()){
int size = queue.size();
dist++;
for(int k =0;k<size;k++){
int[]id = queue.poll();
int r = id[0];
int c =id[1];
if(r-1>=0 && !visited[r-1][c]){
if(matrix[r-1][c]==0) break l;
else{
queue.offer(new int[]{r-1,c});
visited[r-1][c] = true;
}
}
if(r+1<row && !visited[r+1][c]){
if(matrix[r+1][c]==0) break l;
else{
queue.offer(new int[]{r+1,c});
visited[r+1][c] = true;
}
}
if(c-1>=0&& !visited[r] [c-1]){
if(matrix[r][c-1]==0) break l;
else{
queue.offer(new int[]{r,c-1});
visited[r][c-1] = true;
}
}
if(c+1<column&& !visited[r][c+1]){
if(matrix[r][c+1]==0) break l;
else{
queue.offer(new int[]{r,c+1});
visited[r][c+1] =true;
}
}
}
}
}
matrix[i][j]= dist;
}
}
return matrix;
}
}
整个下来,简直就是暴力搜索,在奇淫巧技的LeetCode上那肯定是过不了的。话不多说,呈上奇淫巧技:
class Solution{
static int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int[][] updateMatrix(int[][] matrix){
int row = matrix.length;
int column = matrix[0].length;
boolean[][] visited= new boolean[row][column];
Queue<int[]> queue = new LinkedList();
//先将所有的0存入队列
for(int i=0;i<row;i++){
for(int j =0;j<column;j++){
if(matrix[i][j]==0){
queue.offer(new int[]{i,j});
visited[i][j] = true;
}
}
}
//查找0到1
while(!queue.isEmpty()){
int cur[] = queue.poll();
int r = cur[0];
int c = cur[1];
for(int k=0;k<4;k++){
int next_r = r + dirs[k][0];
int next_c = c + dirs[k][1];
if(next_c>=0&&next_c<column&&next_r>=0&&next_r<row&&!visited[next_r][next_c]){
matrix[next_r][next_c] = matrix[r][c] +matrix[next_r][next_c];
//0到1的最短距离
queue.offer(new int[]{next_r,next_c});
//将1的坐标入队列
visited[next_r][next_c] = true;
//标记已被访问
}
}
}
return matrix;
}
}
将所有的0加入队列中,并用visited数组标记已访问。然后开始将0一一出队列,并搜索每个0的4个尚未访问过的邻居(若没有被访问一定是1,因为所有的0都没被访问过了,而进剩下1没有被访问了。
链接:https://leetcode-cn.com/problems/01-matrix