## # 74. Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

• Integers in each row are sorted from left to right.
• The first integer of each row is greater than the last integer of the previous row.

Example 1:

``````Input:
matrix = [
[1,   3,  5,  7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
``````

Example 2:

``````Input:
matrix = [
[1,   3,  5,  7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
``````

### # Solution

Approach 1: 2D binary search.

Approach 2: Binary search for rows and columns respectively.

Approach 1:

Approach 2:

### # Code (C++)

Approach 1:

``````// 2D binary search.
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rowSize = matrix.size();
if (rowSize == 0)
return false;
int colSize = matrix[0].size();
int tailRow = rowSize - 1;
int tailCol = colSize - 1;
{
int distance = (colSize - headCol) + (tailRow - headRow - 1) * colSize + (tailCol + 1) - 1;
int midRow = headRow + ((distance / 2) / colSize);
int midCol = headCol + ((distance / 2) % colSize);
if (midCol >= colSize)
{
midRow++;
midCol -= colSize;
}
if (matrix[midRow][midCol] == target)
return true;
else if (matrix[midRow][midCol] > target)
{
tailRow = midRow;
tailCol = midCol - 1;
if (tailCol < 0)
{
tailCol = colSize - 1;
tailRow = midRow - 1;
}
}
else
{
{
}
}
}
return false;
}
};
``````

Approach 2:

``````// Binary search for rows and columns respectively.
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rowSize = matrix.size();
if (rowSize == 0)
return false;
int colSize = matrix[0].size();
if (colSize == 0)
return false;

// Binary search for rows.
int tail = rowSize - 1;
int targetRow = -1;
/*
{
if (matrix[mid][0] == target)
return true;
else if (matrix[mid][0] > target)
tail = mid - 1;
else
}
*/
{
if (matrix[mid].front() > target)
tail = mid - 1;
else if (matrix[mid].back() < target)
else
{
targetRow = mid;
break;
}
}

if (targetRow < 0)
return false;

// Binary search for columns.
tail = colSize - 1;