
- 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
Program to find a target value inside given matrix or not in Python
Suppose we have a 2D matrix, where each row and column is sorted in non-decreasing order, we have to check whether given target is present inside it or not.
So, if the input is like
2 | 4 | 30 |
3 | 4 | 31 |
6 | 6 | 32 |
And target = 31, then the output will be True
To solve this, we will follow these steps −
- col := column size of matrix - 1
- for i in range 0 to row size of matrix, do
- while matrix[i, col] > target and col >= 0, do
- col := col - 1
- if matrix[i, col] is same as target, then
- return True
- while matrix[i, col] > target and col >= 0, do
- return False
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix, target): col = len(matrix[0]) - 1 for i in range(len(matrix)): while matrix[i][col] > target and col >= 0: col = col - 1 if matrix[i][col] == target: return True return False ob = Solution() matrix = [ [2, 4, 30], [3, 4, 31], [6, 6, 32] ] target = 31 print(ob.solve(matrix, target))
Input
matrix = [ [2, 4, 30], [3, 4, 31], [6, 6, 32]] target = 31
Output
True
- Related Articles
- Program to check whether given matrix is Toeplitz Matrix or not in Python
- Program to check given point in inside or boundary of given polygon or not in python
- Program to check robot can reach target position or not in Python
- JavaScript program to check if a given matrix is sparse or not
- Find if given matrix is Toeplitz or not in C++
- Program to find number of given operations required to reach Target in Python
- Program to find number of ways to form a target string given a dictionary in Python
- Program to check some elements in matrix forms a cycle or not in python
- Program to find the transpose of given matrix in Python
- Program to check whether robot is moving inside a bounded box or not in Python
- Program to find lowest sum of pairs greater than given target in Python
- Program to find number of sublists whose sum is given target in python
- Program to find nth smallest number from a given matrix in Python
- Program to check if a matrix is Binary matrix or not in C++
- C++ program to find last value of matrix with given constraints

Advertisements