The problem can be approached in a logical way where you loop through the building and check for potential space where tables can be placed, then just return the biggest table found:(可以以逻辑方式解决该问题,其中您可以遍历整个建筑物并检查可以放置表的潜在空间 ,然后仅返回找到的最大表 :)
function biggestTable(grid) {
const tableExist = (x, y, w, h) => {
let exist = 1;
for(let i = 0; i < w ; i++) {
for(let j = 0; j < h ; j++) {
exist &= grid[j + y] !== undefined && grid[j + y][i + x] === 1;
}
}
return exist;
};
const biggestTableAt = (x, y) => {
let max = 0;
for(let w = 1; w <= grid[0].length; w++) {
for(let h = 1; h <= grid.length; h++) {
const table_size = w * h;
if (tableExist(x, y, w, h) && table_size>max) {
max = table_size;
}
}
}
return max;
};
let max = 0;
for(let x = 0; x < grid[0].length; x++) {
for(let y= 0; y < grid.length; y++) {
const table_size = biggestTableAt(x, y);
if (table_size > max) {
max = table_size;
}
}
}
return max;
}
const simple_grid = [
[1, 0, 1, 1, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0]
];
console.log(biggestTable(simple_grid)); //returns 9
const big_grid = [
[1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1],
];
console.log(biggestTable(big_grid)); // returns 18
The accepted response returns 9 for both grids, as it assumes that tables are square instead of rectangular as requested in the question.(接受的响应对于两个网格均返回9,因为它假定表格是正方形而不是问题中要求的矩形 。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…