542. 01 Matrix

本文介绍了一种算法,用于解决给定由0和1组成的矩阵中,每个元素到最近的0的距离问题。通过两次遍历矩阵的方式,从左上角到右下角再反过来进行,确保了每个元素的距离是最小的。此方法适用于矩阵元素不超过10,000的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Subscribe to see which companies asked this question.

Solution:

Tips:

iterator matrix from left up corner to right down. then from right down to left up.

dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1, dp[i + 1][j] + 1, dp[i][j + 1] + 1, dp[i] [j - 1] + 1);


Java Code:

public class Solution {
    public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
        List<List<Integer>> result = new ArrayList<>();
        if (null == matrix) {
            return result;
        }
        
        int m = matrix.size();
        int n = matrix.get(0).size();
        int maxDistance = m * n;
        
        int[][] distance = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                distance[i][j] = matrix.get(i).get(j) == 0 ? 0 : maxDistance;
            }
        }
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                distance[i][j] = i - 1 >= 0 ? Math.min(distance[i - 1][j] + 1, distance[i][j]) : distance[i][j];
                distance[i][j] = j - 1 >= 0 ? Math.min(distance[i][j - 1] + 1, distance[i][j]) : distance[i][j];
            }
        }
        
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                distance[i][j] = i + 1 < m ? Math.min(distance[i + 1][j] + 1, distance[i][j]) : distance[i][j];
                distance[i][j] = j + 1 < n ? Math.min(distance[i][j + 1] + 1, distance[i][j]) : distance[i][j];
            }
        }

        for (int i = 0; i < m; i++) {
            List<Integer> lst = new ArrayList<>();
            for (int j = 0; j < n; j++) {
                lst.add(distance[i][j]);
            }
            result.add(lst);
        }
        
        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值