Search a 2D Matrix II

 

CREATED TIME: Feb 22, 2020 12:44 PM UPDATED TIME: Feb 22, 2020 12:44 PM 난이도: Medium

class Solution { public: bool check_matrix(pair<int, int> point, int n, int m){

        if(!(point.first >= 0 && point.first < n && point.second >= 0 && point.second < m )){
            return false;
        }
        
        return true;
    }
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int n = matrix.size();
        if(n == 0){
            return false;
        }
        int m = matrix[0].size();
        if(m == 0){
            return false;
        }
        pair<int, int> point = {0, m-1};
        
        while(1){
            if (matrix[point.first][point.second] > target){
                point = {point.first, point.second-1};
                
                if(!check_matrix(point, n, m)){
                    return false;
                }
            }else if (matrix[point.first][point.second] < target){
                point = {point.first+1, point.second};
                
                if(!check_matrix(point, n, m)){
                    return false;
                }
            }else{
                return true;
            }
        }
        return false;
    }
};