学习计划算法: 第九天

100 阅读1分钟

矩阵

给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。

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

输入: mat = [[0,0,0],[0,1,0],[0,0,0]]
输出: [[0,0,0],[0,1,0],[0,0,0]]
输入: mat = [[0,0,0],[0,1,0],[1,1,1]]
输出: [[0,0,0],[0,1,0],[1,2,1]]

leetcode-cn.com/problems/01…

class Solution {
    public int[][] updateMatrix(int[][] mat) {
        int row = mat.length;
        int col = mat[0].length;
        for(int i=0; i<row; i++) {
            for(int j=0; j<col; j++){
                if(mat[i][j] ==1 && !((i > 0 && mat[i - 1][j] == 0)
                        || (i < row - 1 && mat[i + 1][j] == 0)
                        || (j > 0 && mat[i][j - 1] == 0)
                        || (j < col - 1 && mat[i][j + 1] == 0))){
                        mat[i][j] = row +col;
                }
            }
        }

        for(int i=0; i<row; i++){
            for(int j=0; j< col; j++){
                if(mat[i][j] ==1){
                    updateMat(mat, row, col, i,j);
                }
            }
        }
        return mat;
    }

    private void updateMat(int[][] mat, int row, int col, int x, int y){
        int[][] arr = new int[][]{{-1,0}, {0,-1}, {1,0},{0,1}};
        for(int i=0; i< arr.length; i++){
            int rx = x + arr[i][0], ry = y + arr[i][1];
            if (rx >= 0 && rx < row
                    && ry >= 0 && ry < col
                    && mat[rx][ry] > mat[x][y] + 1) {
                mat[rx][ry] = mat[x][y] + 1;
                updateMat(mat, row, col, rx, ry);
            }
        }
    }
}