Search a 2D Matrix II in Python


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 −

1471115
2581219
3691622
1013141724
1821232630

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

  • while true

    • 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

    • return false

Example

Let us see the following implementation to get better understanding −

class Solution:
   def searchMatrix(self, matrix, target):
      try:
      length = len(matrix[0])
      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

Input

[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
5

Output

true
raja
Published on 05-Feb-2020 10:28:14
Advertisements