leetcode 542题 01矩阵
题目
给定一个由 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先置为一个无法到达的数,可以免去第二次遍历到最左上角数字时还需要if判断一次。
package com.leetcode.medium;
public class UpdateMatrix {
public int[][] updateMatrix(int[][] matrix) {
if(matrix.length == 0){
return null;
}
int cols = matrix.length;
int rows = matrix[0].length;
for(int i=0;i<cols;i++){
for(int j=0;j<rows;j++){
if(matrix[i][j]==1){
matrix[i][j] = rows + cols;
}
if(i>0){
int up = matrix[i-1][j]+1;
int temp = matrix[i][j];
matrix[i][j]= temp>up?up:temp;
}
if(j>0){
int left = matrix[i][j-1]+1;
int temp = matrix[i][j];
matrix[i][j]= temp>left?left:temp;
}
}
}
for(int col=cols-1;col>=0;col--){
for(int row=rows-1;row>=0;row--){
if(col<cols-1){
int down = matrix[col+1][row]+1;
int temp = matrix[col][row];
matrix[col][row]= temp>down?down:temp;
}
if(row<rows-1){
int right = matrix[col][row+1]+1;
int temp = matrix[col][row];
matrix[col][row]= temp>right?right:temp;
}
}
}
return matrix;
}
public static void main(String[] args) {
int[][] mat = {{0,0,0},{0,1,0},{0,1,0}};
UpdateMatrix um = new UpdateMatrix();
int[][] result = um.updateMatrix(mat);
}
}