Search a 2D Matrix in C++

C++Server Side ProgrammingProgramming

Suppose we have write an efficient algorithm to searches for a value in one m x n matrix. This matrix has some properties like below −

  • Each row is sorted from left to right

  • The first number of each row is greater than the last integer of the previous row.

So if the matrix is like −

1357
10111620
23303450
53627898

And if the target value is 16, then the output will be True.

Let us see the steps −

  • n := number of rows, if n is 0, then return false, m := number of columns, if m = 0, then return false

  • low := 0 and high := n - 1

  • while low < high

    • mid := low + (high - low + 1)/2

    • if mat[mid, 0] <= target, then low := mid, otherwise high := mid - 1

  • rlow := 0 and rhigh := m - 1 and ans := 0

  • while rlow <= rhigh

    • mid := rlow + (rhigh - rlow)/2

    • if mat[low, mid] = target, then ans := 1, and break the loop

    • otherwise when matrix[low, mid] < target, then rlow := mid + 1

    • else rhigh := mid - 1

  • return ans

Example

Let us see the following implementation to get better understanding −

typedef long long int lli;
class Solution {
   public:
   bool searchMatrix(vector<vector<int>>& matrix, int target) {
      lli n,m;
      n = matrix.size();
      if(!n)return false;
      m = matrix[0].size();
      if(!m)return false;
      lli low = 0, high = n-1;
      while(low<high){
         lli mid = low + ( high - low +1)/2;
         if(matrix[mid][0]<=target)low = mid;
         else high = mid -1;
      }
      lli rlow = 0, rhigh = m-1;
      lli ans = 0;
      //cout << low << endl;
      while(rlow<=rhigh){
         lli mid = rlow+(rhigh - rlow)/2;
         if(matrix[low][mid] == target){
            ans =1;
            break;
         } else if(matrix[low][mid]<target)rlow=mid+1;
         else rhigh= mid-1;
      }
      return ans;
   }
};

Input

[[1,3,5,7],[10,11,16,20],[23,30,34,50],[53,62,78,98]]
16

Output

true
raja
Published on 03-Feb-2020 10:03:21
Advertisements