> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/240.-search-a-2d-matrix-ii.md).

# 240. Search a 2D Matrix II

## 1.問題

* 判斷是否可以在矩陣中找到target, 矩陣的特性如下:
  * 每一row的排序為由左到右升冪
  * 每一col的順序為由上到下升冪

![](/files/-LYanOE7Vr365RoKr3cH)

## 2.想法&#x20;

* 提問:
* function header, parameter
* test input
* 說明想法&#x20;
  * 由於此陣列的排列順序為左到右, 上到下ascending排序, 因此可以先從右上角開始, 與target比較, 如果該點大於target, 則左移該點; 如果該點小於target, 則下移該點
* 測試計算複雜度

## 3.程式碼

```
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.size() == 0) {
            return false;
        }
        return search(matrix, target);
    }
private:
    bool search(vector<vector<int>>& matrix, int target){
        int col = matrix[0].size() - 1 ;
        int row = 0;
        while (row < matrix.size() &&
               col >= 0 ) {
            if (matrix[row][col] == target) {
                return true;
            }
            if (matrix[row][col] > target) {
                col--;
            } else if (matrix[row][col] < target) {
                row++;
            }
        }
        
        return false;
    }
};
```
