|
| 1 | +/** |
| 2 | + * Solution: only current element's top left element is 1, the square numbers is possible to increase 1. |
| 3 | + * If the element's left, top is 1, yes, then the square numbers adds 1. Otherwise, set the square number of |
| 4 | + * current element to Min(topleft, left, top) + 1. |
| 5 | + * If current element's top left element is 0, just simply set current element's square number to be 0; |
| 6 | + * The formular is dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1; |
| 7 | + * or dp[i][j] = 0, if matrix[i-1][j-1] == 0 |
| 8 | + * |
| 9 | + *@param {character[][]} matrix |
| 10 | + *@return {number} |
| 11 | + */ |
| 12 | +varmaximalSquare=function(matrix){ |
| 13 | +varrows=matrix.length; |
| 14 | +if(rows===0)return0; |
| 15 | +varcols=matrix[0].length; |
| 16 | +varsquares=[[0]];// the two dimensional array is not fully initialized yet. |
| 17 | +varresult=0; |
| 18 | + |
| 19 | +for(vari=1;i<=rows;i++){ |
| 20 | +squares.push([0]); |
| 21 | +for(varj=1;j<=cols;j++){ |
| 22 | +squares[0][j]=0; |
| 23 | +if(matrix[i-1][j-1]==='1'){ |
| 24 | +squares[i][j]=Math.min(squares[i-1][j],squares[i-1][j-1],squares[i][j-1])+1; |
| 25 | +result=Math.max(result,squares[i][j]); |
| 26 | +}else{ |
| 27 | +// In JavaScript, assign 0 to an undefined element in the array. |
| 28 | +squares[i][j]=0; |
| 29 | +} |
| 30 | +} |
| 31 | +} |
| 32 | +returnresult*result; |
| 33 | +}; |
| 34 | + |
| 35 | +// test cases |
| 36 | +// ["1"] |
| 37 | +// ["1010","1011","1111","1001"] |