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

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