📅  最后修改于: 2023-12-03 15:37:15.241000             🧑  作者: Mango
This is a programming question that was asked in the ISRO CS 2015 exam.
We are given a sorted matrix of integers of size N x M. Each row is sorted in non-decreasing order from left to right whereas each column is sorted in non-decreasing order from top to bottom. We need to design an algorithm to search for a particular element in the matrix in O(N+M) time complexity.
We can start from the top-right corner of the matrix, which is the maximum element in the first row and the minimum element in the last column. We can then compare the target element with this element. If the target element is smaller than the current element, we move to the left. If the target element is larger than the current element, we move to the next row. We repeat this process until we either find the element or reach the end of the matrix.
This algorithm has a time complexity of O(N+M) because in the worst case scenario, we have to move N rows and M columns to find the element.
def search(matrix, target):
if matrix == [] or matrix == [[]]:
return False
# get dimensions of the matrix
n = len(matrix)
m = len(matrix[0])
# start from the top-right corner
row = 0
col = m - 1
# loop until we find the element or reach the end of the matrix
while row < n and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else:
col -= 1
return False
The input to the function is a matrix and a target element. The function returns True if the element is found in the matrix, and False otherwise.
In this article, we designed an algorithm to search for an element in a sorted matrix of size N x M in O(N+M) time complexity. This algorithm is efficient and can be used in real-world applications where we need to search for an element in a large matrix. The code snippet provided above is written in Python, but this algorithm can be implemented in any programming language of your choice.