Leeetcode 221 最大正方形 DP

时间:2021-07-23 17:42:02   收藏:0   阅读:0

技术图片 

  JAVA DP 反向:

public final int maximalSquare(char[][] matrix) {
        int xLen = matrix.length, yLen = matrix[0].length, re = 0;
        int[][] cache = new int[xLen][yLen];
        for (int i = 0; i < xLen; i++)
            for (int j = 0; j < yLen; j++)
                re = Math.max(re, endOf(matrix, i, j, cache));
        return re * re;
    }

    private final int endOf(char[][] matrix, int x, int y, int[][] cache) {
        if (matrix[x][y] == ‘0‘) return 0;
        if (x == 0 || y == 0) return 1;
        if (cache[x][y] != 0) return cache[x][y];
        int re = Math.min(endOf(matrix, x - 1, y, cache), endOf(matrix, x, y - 1, cache));
        re = Math.min(re, endOf(matrix, x - 1, y - 1, cache));
        cache[x][y] = re + 1;
        return cache[x][y];
    }

  JS DP 正向:

/**
 * @param {character[][]} matrix
 * @return {number}
 */
var maximalSquare = function (matrix) {
    let xLen = matrix.length, yLen = matrix[0].length, re = 0, cache = new Array(xLen);
    for (let i = 0; i < xLen; i++) cache[i] = new Array(yLen);
    for (let i = 0; i < xLen; i++) {
        for (let j = 0; j < yLen; j++)
            re = Math.max(re, dp(matrix, i, j, cache));
    }
    return re * re;
};

var dp = function (matrix, x, y, cache) {
    let xLen = matrix.length, yLen = matrix[0].length;
    if (x >= xLen || y >= yLen) return 0;
    if (matrix[x][y] == ‘0‘) return 0;
    if (cache[x][y]) return cache[x][y];
    let child = Math.min(dp(matrix, x + 1, y, cache), dp(matrix, x, y + 1, cache));
    child = Math.min(child, dp(matrix, x + 1, y + 1, cache));
    cache[x][y] = child + 1;
    return cache[x][y];
}

技术图片

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!