# LC74 Search in 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.

# ideas

We can search the matrix using binary search. Since the matrix is sorted in 2d. We can just first go to the middle. If the middle is too large, then we will only search the [0, middle – 1]…

## Index

We will not do 2d search. Instead we will treat this problem as 1D and convert the 1D ranking to 2D position.

``````bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0)
return false;
if (matrix[0].size() == 0)
return false;
int colLen = matrix[0].size();
int rowLen = matrix.size();
int low = 0;
int high = rowLen * colLen - 1;
int mid = -1;
int midX = -1;
int midY = -1;
while (low <= high){
mid = low + (high - low) / 2;
midY = mid / colLen;
midX = mid % colLen;
if (matrix[midY][midX] == target){
return true;
}

if (matrix[midY][midX] > target){
high = mid - 1;
}
else{
low = mid + 1;
}
}
return false;
}

``````

# Take away

When you see efficient algorithm for search, and the input is in any kind of sorted form(2d, 3d… what ever) think binary search