#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
if (rows == 0) return false;
int cols = matrix[0].size();
int r = 0, c = cols - 1; // start top-right
while (r < rows && c >= 0) {
if (matrix[r][c] == target) {
return true; // found target
} else if (matrix[r][c] > target) {
c--; // move left
} else {
r++; // move down
}
}
return false; // not found
}
};
int main() {
vector<vector<int>> matrix = {
{1, 4, 7, 11},
{2, 5, 8, 12},
{3, 6, 9, 16},
{10, 13, 14, 17}
};
int target = 5;
Solution sol;
bool found = sol.searchMatrix(matrix, target);
cout << (found ? "true" : "false") << endl;
return 0;
}int r = 0, c = cols - 1; // start top-right
initialize pointers at top-right corner to begin search
while (r < rows && c >= 0) {
loop while pointers are inside matrix bounds
if (matrix[r][c] == target) {
check if current element is target
return true; // found target
stop search immediately when target found
else if (matrix[r][c] > target) {
if current element is bigger, move left to smaller elements
decrement column to move left
if current element is smaller, move down to bigger elements
increment row to move down