其他分享
首页 > 其他分享> > Leeetcode 221 最大正方形 DP

Leeetcode 221 最大正方形 DP

作者:互联网

 

  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];
}

标签:return,matrix,Leeetcode,int,cache,xLen,re,DP,221
来源: https://www.cnblogs.com/niuyourou/p/15046937.html