class MatrixSearcher {
constructor(matrix) {
this.matrix = matrix;
}
search(target) {
if (this.matrix.length === 0 || this.matrix[0].length === 0) return false;
let row = 0;
let col = this.matrix[0].length - 1;
while (row < this.matrix.length && col >= 0) {
const current = this.matrix[row][col];
if (current === target) {
return true; // found target
} else if (current > target) {
col--; // move left to smaller numbers
} else {
row++; // move down to bigger numbers
}
}
return false; // target not found
}
}
// Driver code
const matrix = [
[1, 4, 7, 11],
[2, 5, 8, 12],
[3, 6, 9, 16],
[10, 13, 14, 17]
];
const target = 5;
const searcher = new MatrixSearcher(matrix);
console.log(searcher.search(target));while (row < this.matrix.length && col >= 0) {
loop while inside matrix bounds
const current = this.matrix[row][col];
get current element to compare
if (current === target) { return true; }
found target, stop search
else if (current > target) { col--; }
current too big, move left to smaller numbers
current too small, move down to bigger numbers