# 240. Search a 2D Matrix II

## 1.問題

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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LYanCMkzToG_dImIg1R%2F-LYanOE7Vr365RoKr3cH%2Fimage.png?alt=media\&token=131be6d7-f330-4e85-be6e-278fdc558628)

## 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;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/240.-search-a-2d-matrix-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
