# LeetCode Search a 2D Matrix II

LeetCode Search a 2D Matrix II
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 in ascending from left to right.
• Integers in each column are sorted in ascending from top to bottom.

For example,
Consider the following matrix:

```[
[1,   4,  7, 11, 15],
[2,   5,  8, 12, 19],
[3,   6,  9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
```

Given target = `5`, return `true`.
Given target = `20`, return `false`.

LeetCode Search a 2D Matrix基础上改动了一点点，但是难度增加不少。这一次，每行和每列都是递增的，但是这一行的行首元素和上一行的行末元素没有大小关系，这种矩阵有点像从左上角递增到右下角的一个曲面，想象一下。

```class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0)return false;
int m = matrix.size(), n = matrix[0].size();
if (n == 0)return false;
int i = 0, j = n - 1;
while (i < m&&j >= 0) {
while (i < m&&matrix[i][j] < target)++i;
if (i >= m)return false;
while (j >= 0 && matrix[i][j] > target)--j;
if (j < 0)return false;
if (matrix[i][j] == target)return true;
}
return false;
}
};
```

```class Solution {
public:
bool quadPart(vector<vector<int>>& matrix, int left, int top, int right, int bottom, int target) {
if (left > right || top>bottom)return false;
if (target<matrix[left][top] || target>matrix[right][bottom])return false;
int midrow = left + (right - left) / 2, midcol = top + (bottom - top) / 2;
if (target == matrix[midrow][midcol])return true;
//if (target > matrix[midrow][midcol]) { // 抛弃左上角
//	return quadPart(matrix, left, midcol + 1, midrow - 1, bottom, target) || // 右上角
//		quadPart(matrix, midrow + 1, top, right, midcol - 1, target) || // 左下角
//		quadPart(matrix, midrow, midcol, right, bottom, target); // 右下角
//}
//else {
//	return quadPart(matrix, left, midcol + 1, midrow - 1, bottom, target) || // 右上角
//		quadPart(matrix, midrow + 1, top, right, midcol - 1, target) || // 左下角
//		quadPart(matrix, left, top, midrow, midcol, target); //左上角
//}
if (target > matrix[midrow][midcol]) { // 抛弃左上角
return quadPart(matrix, left, midcol + 1, midrow, bottom, target) || // 右上角
quadPart(matrix, midrow + 1, top, right, midcol, target) || // 左下角
quadPart(matrix, midrow + 1, midcol + 1, right, bottom, target); // 右下角
}
else {
return quadPart(matrix, left, midcol, midrow - 1, bottom, target) || // 右上角
quadPart(matrix, midrow, top, right, midcol - 1, target) || // 左下角
quadPart(matrix, left, top, midrow - 1, midcol - 1, target); //左上角
}
}
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0)return false;
int m = matrix.size(), n = matrix[0].size();
if (n == 0)return false;
return quadPart(matrix, 0, 0, m - 1, n - 1, target);
}
};
```

This site uses Akismet to reduce spam. Learn how your comment data is processed.