Java in-place DP two traversal AC solution. O(mn) No BFS needed.


  • 2
    public class Solution {
        public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
            final int MAX = matrix.size() + matrix.get(0).size();
            for (int i = 0; i < matrix.size(); i++) {
                for (int j = 0; j < matrix.get(i).size(); j++) {
                    if (matrix.get(i).get(j) == 0) {
                        continue;
                    }
                    int left = j == 0 ? MAX : matrix.get(i).get(j - 1);
                    int up = i == 0 ? MAX : matrix.get(i - 1).get(j);
                    matrix.get(i).set(j, Math.min(left, up) + 1);
                }
            }
            
            for (int i = matrix.size() - 1; i >= 0; i--) {
                for (int j = matrix.get(i).size() - 1; j >= 0; j--) {
                    if (matrix.get(i).get(j) == 0) {
                        continue;
                    }
                    int right = j == matrix.get(i).size() - 1 ? MAX : matrix.get(i).get(j + 1);
                    int down = i == matrix.size() - 1 ? MAX : matrix.get(i + 1).get(j);
                    matrix.get(i).set(j, Math.min(matrix.get(i).get(j), Math.min(right, down) + 1));
                }
            }
            return matrix;
        }
    }
    

  • 0
    H

    No need to check matrix.get(i).get(j) == 0 in the second sweep.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.