Program to search an Element in the Matrix
Definition & Explanation
Example:
Input:
Output:
More Description
Program Logic
Desc
C
Method 1 :
#include <stdio.h>
#include <stdbool.h>
bool searchMatrix(int matrix[5][4], int target) {
int rows = 5, cols = 4;
int row = 0, col = cols - 1;
while (row < rows && col >= 0) {
if (matrix[row][col] == target)
return true;
else if (matrix[row][col] < target)
row++;
else
col--;
}
return false;
}
int main() {
int matrix[5][4] = {
{1, 4, 7, 11},
{2, 5, 8, 12},
{3, 6, 9, 16},
{10, 13, 14, 17},
{18, 21, 23, 26}
};
int target = 9;
if (searchMatrix(matrix, target))
printf("Element %d found in the matrix.\n", target);
else
printf("Element %d not found in the matrix.\n", target);
return 0;
}
Output :
C++
Method 1 :
#include <iostream>
#include <vector>
using namespace std;
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
if (rows == 0) return false;
int cols = matrix[0].size();
int row = 0, col = cols - 1;
while (row < rows && col >= 0) {
if (matrix[row][col] == target)
return true;
else if (matrix[row][col] < target)
row++;
else
col--;
}
return false;
}
int main() {
vector<vector<int>> matrix = {
{1, 4, 7, 11},
{2, 5, 8, 12},
{3, 6, 9, 16},
{10, 13, 14, 17},
{18, 21, 23, 26}
};
int target = 9;
if (searchMatrix(matrix, target))
cout << "Element " << target << " found in the matrix." << endl;
else
cout << "Element " << target << " not found in the matrix." << endl;
return 0;
}
Output :
JAVA
Method 1 :
public class Main {
public static boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
if (rows == 0) return false;
int cols = matrix[0].length;
int row = 0, col = cols - 1;
while (row < rows && col >= 0) {
if (matrix[row][col] == target)
return true;
else if (matrix[row][col] < target)
row++;
else
col--;
}
return false;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 4, 7, 11},
{2, 5, 8, 12},
{3, 6, 9, 16},
{10, 13, 14, 17},
{18, 21, 23, 26}
};
int target = 9;
if (searchMatrix(matrix, target))
System.out.println("Element " + target + " found in the matrix.");
else
System.out.println("Element " + target + " not found in the matrix.");
}
}
Output :
Python
Method 1 :
def search_matrix(matrix, target):
if not matrix or not matrix[0]:
return False
rows, cols = len(matrix), len(matrix[0])
row, col = 0, cols - 1
while row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else:
col -= 1
return False
# Example usage:
matrix = [
[1, 4, 7, 11],
[2, 5, 8, 12],
[3, 6, 9, 16],
[10, 13, 14, 17],
[18, 21, 23, 26]
]
target = 9
print(search_matrix(matrix, target))
Output :
True