编辑代码

#include <iostream>
#include <vector>

bool searchMatrix(const std::vector<std::vector<int>>& matrix, int target) {
    if (matrix.empty() || matrix[0].empty()) {
        return false;
    }

    int rows = matrix.size();
    int cols = matrix[0].size();

    // 从右上角开始查找
    int row = 0;
    int col = cols - 1;

    while (row < rows && col >= 0) {
        if (matrix[row][col] == target) {
            return true;
        } else if (matrix[row][col] > target) {
            col--;  
        } else {
            row++;  
        }
    }

    return false;  
}

int main() {
    std::vector<std::vector<int>> matrix = {
        {1, 2, 8, 9},
        {2, 4, 9, 12},
        {4, 7, 10, 13},
        {6, 8, 11, 15}
    };

    int target1 = 7;
    int target2 = 5;

    std::cout << std::boolalpha;  
    std::cout << "查找 " << target1 << " 的结果是: " << searchMatrix(matrix, target1) << std::endl;
    std::cout << "查找 " << target2 << " 的结果是: " << searchMatrix(matrix, target2) << std::endl;

    return 0;
}