# leetcode Search a 2D Matrix II

xiaoxiao2021-02-28  4

# 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.

## 代码详情：

class Solution { public:     bool searchMatrix(vector<vector<int>>& matrix, int target) {         if (matrix.size() == 0) {             return false;         } else if (matrix[0].size() == 0) {             return false;         } else {             int flag = 0;             int i = matrix.size()-1;             int j = matrix[0].size()-1;             search(matrix,0,i,0,j,target,flag);             if (flag == 0)                 return false;             else                 return true;         }              }     void search(vector<vector<int>>& matrix, int x1, int x2, int y1, int y2, int target, int& flag) {         int x = (x1+x2)/2;         int y = (y1+y2)/2;         if (matrix[x][y] == target) {             flag=1;         } else if (matrix[x][y] < target) {             if (y+1 <= y2 && flag == 0) {                 search(matrix, x1, x2, y+1, y2,target,flag);             }             if (x+1 <= x2 && flag == 0) {                 search(matrix,x+1,x2,y1,y,target,flag);             }                      } else if (matrix[x][y] > target) {             if (y-1 >= y1 && flag == 0) {                 search(matrix, x1, x2, y1, y-1,target,flag);             }             if (x-1 >= x1 && flag == 0) {                 search(matrix,x1,x-1,y,y2,target,flag);             }         }     } };