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

以上啰里啰嗦一大堆,其实意思就是修改所有非0元素的值,为当前元素和最近的0的距离。

class Solution {
    private int[][] matrix;
    private int[][] res;
    private int x;
    private int y;

    public int[][] updateMatrix(int[][] matrix) {
        this.matrix = matrix;
        this.x = matrix.length;
        this.y = matrix[0].length;
        this.res = new int[x][y];
        // 循环二维数组
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                // 找到所有的非0元素
                if (matrix[i][j] != 0) {
                    this.getDis(i, j, 1);
                }
            }
        }
        return res;
    }

    // i,j 为当前元素在二维数组下标,dis为距离 默认为1
    private void getDis(int i, int j, int dis) {
        // 这个k可以理解为以当前元素为中心扩散的层级
        for (int k = 0; k <= dis; k++) { 
            int x1 = i + k;
            int x2 = i - k; 
            int y1 = j + dis - k;
            int y2 = j - dis + k;
            // 判断当前元素上下左右四个方向的元素值找到距离当前位置最近的0
            if (x1 < x && y1 < y && matrix[x1][y1] == 0) {
                res[i][j] = dis;
                break;
            }
            if (x1 < x && y2 >= 0 && matrix[x1][y2] == 0) {
                res[i][j] = dis;
                break;
            }
            if (x2 >= 0 && y1 < y && matrix[x2][y1] == 0) {
                res[i][j] = dis;
                break;
            }
            if (x2 >= 0 && y2 >= 0 && matrix[x2][y2] == 0) {
                res[i][j] = dis;
                break;
            }
        }
        // 如果当前元素值为0,则继续搜索更外圈的元素
        if (res[i][j] == 0) {
            this.getDis(i, j, ++dis);
        }
    }
}

执行用时:6 ms

内存消耗:43.1 MB

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章