Skip to content

Instantly share code, notes, and snippets.

@AlexJuarez
Created June 20, 2020 01:14
Show Gist options
  • Save AlexJuarez/79cee45fd830eb1e9eb81bc4c09866dc to your computer and use it in GitHub Desktop.
Save AlexJuarez/79cee45fd830eb1e9eb81bc4c09866dc to your computer and use it in GitHub Desktop.
Find in 2d matrix
right.
const exampleMatrix = [
[ 1, 2, 6, 10, 17],
[ 3, 5, 8, 12, 19],
[ 7, 9, 13, 15, 24],
[11, 14, 16, 20, 26],
[18, 22, 25, 29, 30],
];
const exampleTarget1 = 13; // return true
const exampleTarget2 = 9; // return true
const exampleTarget3 = 4; // return false
function find(target, M, i= 0, j = M.length - 1, n = 0, m = M[i].length - 1) {
if (M[i][n] > target || M[j][m] < target) {
return false;
}
if (j - i < 3 && m - n < 3) {
for (let k = i; k <= j; k++) {
for (let c = n; c <= m; c++) {
if (M[k][c] === target) return true;
}
}
return false;
} else {
const m1 = Math.floor((i+j)/2);
const m2 = Math.floor((n+m)/2);
return find(target, M, i, m1, n, m2) || find(target, M, m1, j, n, m2) || find(target, M, i, m1, m2, m) || find(target, M, m1, j, m2, m);
}
}
console.log(find(exampleTarget1, exampleMatrix))
console.log(find(exampleTarget2, exampleMatrix))
console.log(find(exampleTarget3, exampleMatrix))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment