Can you change the input and return type to be a int[][] for Java ?


  • 10

    List seems to be weird. Other similar matrix problems all use int[][]. why is this special?


  • 1

    I bet in a real interview, the interviewer will feel much more comfortable if you choose int[][] rather than the List of List.


  • 0

    We've changed the input and output type for Java,

    Thanks for pointing out!


  • 2
    Y
    public int[][] updateMatrix(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        int[][] ans = new int[m][n];
        for (int[] row : ans)       
            Arrays.fill(row, m + n);                
    
        // top-left to bottom-right         
        for (int r = 0; r < m; r++) {       
            for (int c = 0; c < n; c++) {                   
                if (matrix[r][c] == 0) ans[r][c] = 0;                                              
                else {
                    if (r > 0) ans[r][c] = Math.min(ans[r][c], 1 + ans[r - 1][c]);
                    if (c > 0) ans[r][c] = Math.min(ans[r][c], 1 + ans[r][c - 1]);
                }
            }                           
        }
                                                                    
        // bottom-right to top-left
        for (int r = m - 1; r >= 0; r--) {                                          
            for (int c = n - 1; c >= 0; c--) {              
                if (matrix[r][c] == 0) ans[r][c] = 0;
                else {
                    if (r < m - 1) ans[r][c] = Math.min(ans[r][c], 1 + ans[r + 1][c]); 
                    if (c < n - 1) ans[r][c] = Math.min(ans[r][c], 1 + ans[r][c + 1]);
                }                                                   
            }
        }                                           
                                                    
        return ans;
    }
    

Log in to reply
 

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