java自习室 day12

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
注意:

给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。

采用动态规划思路,正向反向各遍历一次二维数组,将最小值写入当前位置。第一次遍历时,将遇到的1先置为一个无法到达的数,可以免去第二次遍历到最左上角数字时还需要if判断一次。

package com.leetcode.medium;

public class UpdateMatrix {
    public int[][] updateMatrix(int[][] matrix) {
        if(matrix.length == 0){
            return null;
        }

        int cols = matrix.length;
        int rows = matrix[0].length;
        for(int i=0;i<cols;i++){
            for(int j=0;j<rows;j++){
                if(matrix[i][j]==1){
                    matrix[i][j] = rows + cols;
                }
                if(i>0){
                    int up = matrix[i-1][j]+1;
                    int temp = matrix[i][j];
                    matrix[i][j]= temp>up?up:temp;
                }
                if(j>0){
                    int left = matrix[i][j-1]+1;
                    int temp = matrix[i][j];
                    matrix[i][j]= temp>left?left:temp;
                }
            }
        }

        for(int col=cols-1;col>=0;col--){
            for(int row=rows-1;row>=0;row--){
                if(col<cols-1){
                    int down = matrix[col+1][row]+1;
                    int temp = matrix[col][row];
                    matrix[col][row]= temp>down?down:temp;
                }
                if(row<rows-1){
                    int right = matrix[col][row+1]+1;
                    int temp = matrix[col][row];
                    matrix[col][row]= temp>right?right:temp;
                }

            }
        }
        return matrix;
    }

    public static void main(String[] args) {
        int[][] mat = {{0,0,0},{0,1,0},{0,1,0}};
        UpdateMatrix um = new UpdateMatrix();
        int[][] result = um.updateMatrix(mat);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值