Last active
May 11, 2021 00:03
-
-
Save Angelfire/698a7ec23518e058b956fb84a9c88385 to your computer and use it in GitHub Desktop.
The largest square sub-matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Casey has a square image made up of black and white pixels | |
represented as 0 and 1 respectively. As part of an image analysis | |
process, Casey needs to determine the size of the largest square area | |
of white pixels. Given a 2-dimensional square matrix that represents | |
the image, write a function to determine the length of a side of the | |
largest square area made up of white pixels. | |
For example, the n x n = 5 x 5 matrix of pixels is represented as arr = | |
[[1,1,1,1,1], [1,1,1,0,0], [1,1,1,0,0], [1,1,1,0,0], [1,1,1,1,1]. A diagram of | |
the matrix is: | |
1 1 1 1 1 | |
1 1 1 0 0 | |
1 1 1 0 0 | |
1 1 1 0 0 | |
1 1 1 1 1 | |
The largest square sub-matrix is 3 x 3 in size starting at position (0, 0), | |
(1, 0) or (2, 0). The expected return value is 3. | |
*/ | |
/** | |
* Create a multidimensional array n*m | |
* @param {number} n columns | |
* @param {number} m rows | |
*/ | |
function multidimensionalArray(n, m) { | |
let sub = new Array(n); | |
for (let i = 0; i < sub.length; i++) { | |
sub[i] = new Array(m); | |
} | |
return sub; | |
} | |
/** | |
* | |
* @param {array} arr | |
*/ | |
function largestMatrix(arr) { | |
const cols = arr.length; | |
const rows = arr[0].length; | |
let maxSize = 0; | |
// here we need to create a multidimensional array based on the numbers of cols and rows, can be filled of zeros | |
let sub = multidimensionalArray(cols, rows); | |
// copy the first row | |
for (let i = 0; i < cols; i++) { | |
sub[0][i] = arr[0][i]; | |
} | |
// copy the first column | |
for (let i = 0; i < rows; i++) { | |
sub[i][0] = arr[i][0]; | |
} | |
// for the rest of the matrix | |
for (let i = 1; i < rows; i++) { | |
for (let j = 1; j < cols; j++) { | |
if (arr[i][j] === 1) { | |
sub[i][j] = Math.min(sub[i - 1][j - 1], Math.min(sub[i][j - 1], sub[i - 1][j])) + 1; | |
} else { | |
sub[i][j] = 0; | |
} | |
} | |
} | |
// find the maximum size of the matrix | |
for (let i = 0; i < rows; i++) { | |
for (let j = 0; j < cols; j++) { | |
if (sub[i][j] > maxSize) { | |
maxSize = sub[i][j]; | |
} | |
} | |
} | |
return maxSize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment