Java Concise Without BFS Solution O(1) Space


  • 0
    public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
        int n = matrix.size(), m = matrix.get(0).size(), numRemaining = n*m;
        for (int i=0;i<=n+m;i++) 
            for (int j=0;j<n;j++) 
                for (int k=0;k<m;k++) {
                    if (i == 0) {
                        if (matrix.get(j).get(k) == 1) matrix.get(j).set(k, -2);
                        else numRemaining--;
                    }
                    if (matrix.get(j).get(k) == -2 && 
                        (j>0 && matrix.get(j-1).get(k) == i-1 ||
                        j<n-1 && matrix.get(j+1).get(k) == i-1 ||
                        k>0 && matrix.get(j).get(k-1) == i-1 ||
                        k<m-1 && matrix.get(j).get(k+1) == i-1)) {matrix.get(j).set(k,i); numRemaining--;}
                    if (numRemaining == 0) return matrix;
                }
        return matrix;
    }
    

Log in to reply
 

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