【LeetCode】 542. 01 Matrix 01 矩阵(Medium)(JAVA)

【LeetCode】 542. 01 Matrix 01 矩阵(Medium)(JAVA)

题目地址: https://leetcode.com/problems/01-matrix/

题目描述:

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,0]]

Output:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

Example 2:

Input:
[[0,0,0],
 [0,1,0],
 [1,1,1]]

Output:
[[0,0,0],
 [0,1,0],
 [1,2,1]]

Note:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.

题目大意

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

解题方法

1、从上往下,从左往右遍历,判断最近的位置
2、从下往上,从右往左遍历,判断最近的位置

class Solution {
    public int[][] updateMatrix(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return matrix;
        int max = matrix.length + matrix[0].length;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == 0) continue;
                if (i == 0 && j == 0) {
                    matrix[i][j] = max;
                } else if (i == 0) {
                    matrix[i][j] = Math.min(matrix[i][j - 1] + 1, max);
                } else if (j == 0) {
                    matrix[i][j] = Math.min(matrix[i - 1][j] + 1, max);
                } else {
                    matrix[i][j] = Math.min(Math.min(matrix[i - 1][j], matrix[i][j - 1]) + 1, max);
                }
            }
        }
        for (int i = matrix.length - 1; i >= 0; i--) {
            for (int j = matrix[0].length - 1; j >= 0; j--) {
                if (matrix[i][j] == 0) continue;
                if (i == matrix.length - 1 && j == matrix[0].length - 1) {
                    matrix[i][j] = matrix[i][j];
                } else if (i == matrix.length - 1) {
                    matrix[i][j] = Math.min(matrix[i][j + 1] + 1, matrix[i][j]);
                } else if (j == matrix[0].length - 1) {
                    matrix[i][j] = Math.min(matrix[i + 1][j] + 1, matrix[i][j]);
                } else {
                    matrix[i][j] = Math.min(Math.min(matrix[i + 1][j], matrix[i][j + 1]) + 1, matrix[i][j]);
                }
            }
        }
        return matrix;
    }
}

执行用时 : 7 ms, 在所有 Java 提交中击败了 97.79% 的用户
内存消耗 : 43.2 MB, 在所有 Java 提交中击败了 100.00% 的用户

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/105543229