2019.11.4 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
这题直接用回溯法必然会超时,矩阵问题可以考虑用动态规划的方法。
建立dp数组,dp[i][j]代表位置ij到最近的0的距离,初始值为Integer.MAX_VALUE-1。对矩阵进行两次遍历。
第一次遍历从左上角开始朝右下,每一个位置到左上部分的到0的最近距离为左邻居和上邻居的较小值+1,状态转移方程:
Math.min(dp[i][j], dp[i - 1][j] + 1, dp[i][j - 1] + 1);
第一次遍历从右下角开始朝左上,每一个位置到右下部分的到0的最近距离为右邻居和下邻居的较小值+1,状态转移方程:
Math.min(dp[i][j], dp[i + 1][j] + 1, dp[i][j + 1] + 1);
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.
给定一个由 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。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。
import java.util.Arrays;
import java.util.LinkedList;
/**
*
* 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.
* 给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
* 两个相邻元素间的距离为 1 。
*
*/
public class Matrix01 {
//BFS超时
public int[][] updateMatrix(int[][] matrix) {
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(matrix[i][j] != 0){
Solution(matrix, i, j);
}
}
}
return matrix;
}
class Point{
int x;
int y;
Point(int px, int py)