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的都記錄下來,那么邊長(zhǎng)為2的方塊只可能以這些點(diǎn)為起點(diǎn)。
遍歷先前的記錄,找到真的有邊長(zhǎng)為2的方塊的起點(diǎn),更新記錄,再去找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;
};
嗯,這個(gè)方法的運(yùn)行時(shí)間成功的擊敗了4%的人。。。。。。。。。。
看了人家的方法。。。。。
利用這個(gè)矩陣邊遍歷邊記錄以這個(gè)點(diǎn)做右下角能達(dá)到的最大的方塊的邊長(zhǎng),有以下2種情況:
matrix[0][j]和matrix[i][0],第一行和第一列,如果是‘1’,那就意味著這個(gè)點(diǎn)的記錄就是1,因?yàn)橐呀?jīng)在邊上了,以它為右下角并不能組成更大的正方形,如果是‘0’那自然就是0了。
對(duì)于其他的點(diǎn),如果是0,當(dāng)然只可能是0了,是1的話就取:
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;
};