20ms Same DP idea but faster


  • 0
    S
    public int[][] updateMatrix(int[][] m) {
            int[][] dp = new int[m.length][m[0].length];
            for(int i = 0; i < m.length; i++){
                for(int j = 0; j < m[0].length; j++){
                    if(m[i][j] == 1){
                        if(i == 0 || j == 0){
                            int x = i == 0 ? Integer.MAX_VALUE : dp[i - 1][j];
                            int y = j == 0 ? Integer.MAX_VALUE : dp[i][j - 1];
                            int temp = Math.min(x, y);
                            dp[i][j] = temp == Integer.MAX_VALUE ? temp : temp + 1;
                        }else{
                            int temp = Math.min(dp[i - 1][j], dp[i][j - 1]);
                            dp[i][j] = temp == Integer.MAX_VALUE ? temp : temp + 1;
                        }
                    }
                }
            }
            for(int i = dp.length - 1; i >= 0; i--){
                for(int j = dp[0].length - 1; j >= 0; j--){
                    if(m[i][j] == 1){
                        if(i + 1 >= dp.length || j + 1 >= dp[0].length){
                            int x = i + 1 >= dp.length ? Integer.MAX_VALUE : dp[i + 1][j];
                            int y = j + 1 >= dp[0].length ? Integer.MAX_VALUE : dp[i][j + 1];
                            int temp = Math.min(x, y);
                            dp[i][j] = temp == Integer.MAX_VALUE ? dp[i][j] : Math.min(dp[i][j], temp + 1);
                        }else{
                            int temp = Math.min(dp[i + 1][j], dp[i][j + 1]);
                            dp[i][j] = temp == Integer.MAX_VALUE ? dp[i][j] : Math.min(dp[i][j], temp + 1);
                        }
                    }
                }
            }
            return dp;
        }
    

Log in to reply
 

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