Suppose we have one m x n matrix. We have to write an efficient algorithm that searches for a value in that matrix. This matrix has the following properties −
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
So if the matrix is like −
If target is 5, then return true, if target is 20, then return false
To solve this, we will follow these steps −
len := number of columns, c1 := 0, c2 := len – 1
if matrix[c1, c2] = target, then return true
else if matrix[c1, c2] > target, then c2 := c2 – 1, continue
c1 := c1 + 1
if c1 >= row count or c2 < 0, then return false
Let us see the following implementation to get better understanding −
class Solution: def searchMatrix(self, matrix, target): try: length = len(matrix) counter1, counter2 = 0, length-1 while True: if matrix[counter1][counter2] == target: return True elif matrix[counter1][counter2]>target: counter2-=1 continue counter1 = counter1 + 1 if counter1 >= len(matrix) or counter2<0: return False except: return False