Search in a Row-Wise and Column-Wise Sorted Matrix
Problem
Given a matrix where each row is sorted in ascending order and each column is sorted in ascending order, find whether a given number exists in the matrix.
Example:
Input:
matrix = [
[1, 4, 7, 11],
[2, 5, 8, 12],
[3, 6, 9, 16],
[10, 13, 14, 17]
], target = 5
Output: true
Solution
— Staircase Search:
Code
public class SearchSortedMatrix {
public static boolean searchMatrix(int[][] matrix, int target) {
int row = 0;
int col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] == target) return true;
else if (matrix[row][col] > target) col--;
else row++;
}
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}
};
System.out.println(searchMatrix(matrix, 5));
}
}def search_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
else:
row += 1
return False
matrix = [[1, 4, 7, 11], [2, 5, 8, 12], [3, 6, 9, 16], [10, 13, 14, 17]]
print(search_matrix(matrix, 5))