Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 3056b07

Browse files
Maximal Square
1 parent 78f18fc commit 3056b07

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

LeetcodeProblems/Maximal_Square.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
221. Maximal Square
3+
4+
https://leetcode.com/problems/maximal-square/
5+
6+
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
7+
8+
Example:
9+
10+
Input:
11+
12+
1 0 1 0 0
13+
1 0 1 1 1
14+
1 1 1 1 1
15+
1 0 0 1 0
16+
17+
Output: 4
18+
*/
19+
20+
/**
21+
* @param {character[][]} matrix
22+
* @return {number}
23+
*/
24+
var maximalSquare = function(matrix) {
25+
var maxSquare = 0;
26+
for(var i = 0; i < matrix.length; i++) {
27+
for(var j = 0; j < matrix[0].length; j++) {
28+
if(matrix[i][j] === "1") { // found a 1
29+
const currentMaxSideLength = getCurrentMaxSideLength(matrix, i, j);
30+
if(currentMaxSideLength ** 2 > maxSquare)
31+
maxSquare = currentMaxSideLength ** 2;
32+
}
33+
}
34+
}
35+
36+
return maxSquare;
37+
};
38+
39+
var getCurrentMaxSideLength = function(matrix, i, j) {
40+
var max = 1;
41+
while(i + max < matrix.length && j + max < matrix[0].length) {
42+
var lastRow = i + max;
43+
var lastCol = j + max;
44+
45+
// check last column
46+
var iterRow = i;
47+
while(iterRow <= lastRow){
48+
if(matrix[iterRow][lastCol] === "0")
49+
return max;
50+
51+
iterRow++;
52+
}
53+
54+
// check last row
55+
var iterCol = j;
56+
while(iterCol <= lastCol) {
57+
if(matrix[lastRow][iterCol] === "0")
58+
return max;
59+
iterCol++;
60+
}
61+
62+
max++;
63+
}
64+
65+
return max;
66+
}
67+
68+
var main = function() {
69+
console.log(maximalSquare([["1","0"]]));
70+
console.log(maximalSquare([["1"]]));
71+
console.log(maximalSquare([["0"]]));
72+
console.log(
73+
maximalSquare([["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]])
74+
);
75+
}
76+
77+
module.exports.main = main

0 commit comments

Comments
 (0)