Last active
March 11, 2022 02:23
-
-
Save mchambaud/f98a66a7e3190340ea1673e6a4765123 to your computer and use it in GitHub Desktop.
BitmapHoles / 2D Matrix
This file contains 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
function searchChallenge(strArr: string[]): number { | |
let contiguousRegions = 0; | |
const matrix: number[][] = strArr.map((x: string): number[] => x.split('') | |
.map((y: string): number => +y)); | |
const search = (row: number, col: number) => { | |
if (row >= 0 && row < matrix.length && col >= 0 && col < matrix[row].length && matrix[row][col] === 0) { | |
matrix[row][col] = 2; | |
// up | |
search(row - 1, col); | |
// down | |
search(row + 1, col); | |
// left | |
search(row, col - 1); | |
// right | |
search(row, col + 1); | |
} | |
} | |
matrix.forEach((row: number[], rowIndex: number) => { | |
row.forEach((value: number, colIndex: number) => { | |
if (value !== 0) return; | |
contiguousRegions++; | |
search(rowIndex, colIndex); | |
}) | |
}); | |
return contiguousRegions; | |
} | |
console.log(searchChallenge(["10111", "10101", "11101", "11101"])); // 2 | |
console.log(searchChallenge(["10111", "10101", "11101", "11111"])); // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment