221. Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 4.
找到最大的全是1的方塊。
我最開始的想法比較笨。。。
先走一遍矩陣,把是1的都記錄下來,那么邊長為2的方塊只可能以這些點為起點。
遍歷先前的記錄,找到真的有邊長為2的方塊的起點,更新記錄,再去找3的。

var maximalSquare = function(matrix) {
    var row = matrix.length;
    if (row===0)
        return 0;
    var col = matrix[0].length;
    var count = 0;
    var rec = [];
    var newRec = [];
    for (let i = 0;i < row;i++) {
        for (let j = 0;j < col;j++) {
            if (matrix[i][j]==='1') 
                rec.push([i,j]);
        }
    }
    while (rec.length!==0) {
        count++;
        check:while (rec.length!==0) {
            let nowCheck = rec.pop();
            let a = nowCheck[0];
            let b = nowCheck[1];
            let c = nowCheck[0] + count;
            let d = nowCheck[1] + count;
            if (c >= row||d >= col)
                continue;
            for(let i = a;i <= c;i++) {
                for (let j = b;j <= d;j++) {
                    if (matrix[i][j]==='0')
                        continue check;
                }
            }
            newRec.push([a,b]);
        }
        rec = newRec;
        newRec = [];
    }
    return count*count;
};

嗯,這個方法的運行時間成功的擊敗了4%的人。。。。。。。。。。
看了人家的方法。。。。。
利用這個矩陣邊遍歷邊記錄以這個點做右下角能達到的最大的方塊的邊長,有以下2種情況:
matrix[0][j]和matrix[i][0],第一行和第一列,如果是‘1’,那就意味著這個點的記錄就是1,因為已經(jīng)在邊上了,以它為右下角并不能組成更大的正方形,如果是‘0’那自然就是0了。
對于其他的點,如果是0,當然只可能是0了,是1的話就?。?/p>

min(matrix[i - 1][j - 1], matrix[i - 1][j], matrix[i][j - 1]) + 1
var maximalSquare = function(matrix) {
    let m = matrix.length;
    if (m === 0) return 0;
    var n = matrix[0].length;
    var maxsize = 0;
    //利用原來的數(shù)組,
    for (let j = 0; j < n; j++) {
        matrix[0][j] = matrix[0][j] - '0';
        maxsize = Math.max(maxsize, matrix[0][j]);
    }
    for (let i = 1; i < m; i++) {
        matrix[i][0] = matrix[i][0] - '0';
        maxsize = Math.max(maxsize, matrix[i][0]);
    }
    for (let i = 1; i < m; i++) {
        for (let j = 1; j < n; j++) {
            if (matrix[i][j] == '1') {
                matrix[i][j] = Math.min(matrix[i - 1][j - 1], matrix[i - 1][j], matrix[i][j - 1]) + 1;
                maxsize = Math.max(maxsize, matrix[i][j]);
            }
        }
    }
    return maxsize * maxsize;
};
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容