|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function maximalSquare(strArr) take |
| 3 | + * the strArr parameter being passed which will be a 2D matrix of 0 and 1's, and |
| 4 | + * determine the area of the largest square submatrix that contains all 1's. A |
| 5 | + * square submatrix is one of equal width and height, and your program should |
| 6 | + * return the area of the largest submatrix that contains only 1's. For example: |
| 7 | + * if strArr is ["10100", "10111", "11111", "10010"] then this looks like the |
| 8 | + * following matrix: |
| 9 | + * |
| 10 | + * 1 0 1 0 0 |
| 11 | + * 1 0 1 1 1 |
| 12 | + * 1 1 1 1 1 |
| 13 | + * 1 0 0 1 0 |
| 14 | + * |
| 15 | + * For the input above, you can see the bolded 1's create the largest square |
| 16 | + * submatrix of size 2x2, so your program should return the area which is 4. You |
| 17 | + * can assume the input will not be empty. |
| 18 | + * |
| 19 | + * https://www.coderbyte.com/results/bhanson:Maximal%20Square:JavaScript |
| 20 | + * |
| 21 | + * @param {array} strArr |
| 22 | + * @return {number} area of max square |
| 23 | + */ |
| 24 | +function maximalSquare(strArr) { |
| 25 | + let maxSquareSize = 0; |
| 26 | + |
| 27 | + strArr.forEach((row, rowIndex) => { |
| 28 | + row.split('').forEach((col, colIndex) => { |
| 29 | + const maxPossibleSquareSize = Math.min( |
| 30 | + strArr.length - rowIndex, |
| 31 | + strArr[0].length - colIndex |
| 32 | + ); |
| 33 | + |
| 34 | + // Try all square sizes from this position |
| 35 | + for (let size = 1; size <= maxPossibleSquareSize; size++) { |
| 36 | + if ( |
| 37 | + isSquare(strArr, colIndex, rowIndex, size) && |
| 38 | + size > maxSquareSize |
| 39 | + ) { |
| 40 | + maxSquareSize = size; |
| 41 | + } |
| 42 | + } |
| 43 | + }); |
| 44 | + }); |
| 45 | + |
| 46 | + return maxSquareSize * maxSquareSize; |
| 47 | +} |
| 48 | + |
| 49 | +function isSquare(matrix, x, y, squareSize) { |
| 50 | + for (let row = y; row < y + squareSize; row++) { |
| 51 | + for (let col = x; col < x + squareSize; col++) { |
| 52 | + if (matrix[row][col] === '0') { |
| 53 | + return false; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + return true; |
| 58 | +} |
| 59 | + |
| 60 | +module.exports = maximalSquare; |
0 commit comments