
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 −
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 |
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
Let us see the following implementation to get better understanding −
Example
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 ob1 = Solution() print(ob1.searchMatrix([[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))
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
- Related Articles
- Search a 2D Matrix in C++
- How to plot a 2D matrix in Python with colorbar Matplotlib?
- Word Search II in Python
- Find the number of distinct islands in a 2D matrix in Python
- Breadth First Search on Matrix in Python
- Maximum sum rectangle in a 2D matrix
- Spiral Matrix II in Python
- Print a 2D Array or Matrix in Java
- Construct a linked list from 2D matrix in C++
- Search in Rotated Sorted Array II in Python
- Print concentric rectangular pattern in a 2d matrix in C++
- Maximum sum rectangle in a 2D matrix | DP-27 in C++
- Construct a linked list from 2D matrix (Iterative Approach) in C++
- Check for possible path in 2D matrix in C++
- Prefix Sum of Matrix (Or 2D Array) in C++

Advertisements