Saturday, January 30, 2016

Searching an element in 2D sorted matrix

Problem:
Write an efficient program that searches for a value in an n x m sorted matrix. This matrix is sorted along the rows and columns.
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool find(int mat[][], int N, int target) {
 
  if (target < mat[0][0] || target > mat[N-1][N-1])
     return false;
   
  int row = 0;
  int col = N-1;
 
  while (row <= N-1 && col >= 0) {
    if (mat[row][col] < target)
      row++;
    else if (mat[row][col] > target)
      col--;
    else
      return true;
  }
  return false;
}

No comments:

Post a Comment