Created
March 6, 2019 00:11
-
-
Save rix501/2576f2db02586333caf7d06b42ba5c2d to your computer and use it in GitHub Desktop.
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
const image1 = [ | |
[0,1,1,1,1,1], | |
[1,1,1,0,0,1], | |
[1,0,1,0,0,1], | |
[1,0,1,1,1,1], | |
[0,1,1,0,0,0], | |
] | |
// O( N * M ) | |
// Memory = N * (M/2) | |
const findRectangles = (image) => { | |
const rectangles = []; | |
const openColumnRects = {}; | |
let lastOpenRect = null; | |
image.forEach((row, y) => { | |
let isOpenRow = false; | |
row.forEach((cell, x) => { | |
const openColumnRect = openColumnRects[x]; | |
switch (cell) { | |
case 0: | |
if (!isOpenRow && !openColumnRect) { | |
const rect = { x, y, width: 1, height: 1 }; | |
rectangles.push(rect); | |
openColumnRects[x] = rect; | |
lastOpenRect = rect; | |
isOpenRow = true; | |
break; | |
} | |
if (openColumnRect) { | |
openColumnRect.height = openColumnRect.height + 1; | |
lastOpenRect = openColumnRect; | |
isOpenRow = true; | |
break; | |
} | |
if (isOpenRow) { | |
lastOpenRect.width = lastOpenRect.width + 1; | |
break; | |
} | |
break; | |
case 1: | |
default: | |
isOpenRow = false; | |
lastOpenRect = null; | |
if (openColumnRect) { | |
openColumnRects[x] = null; | |
} | |
break; | |
} | |
}); | |
}); | |
return rectangles; | |
} | |
console.log(findRectangles(image1)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment