|
| 1 | +package com.thealgorithms.matrix; |
| 2 | + |
| 3 | +/** |
| 4 | + * Two variations of searching in a 2D matrix |
| 5 | + * |
| 6 | + * Variation 1: |
| 7 | + * - Each row is sorted left to right |
| 8 | + * - Each column is sorted top to bottom |
| 9 | + * |
| 10 | + * Variation 2: |
| 11 | + * - The matrix is a flattened sorted array |
| 12 | + * - i.e., row 0 ends, row 1 continues (matrix is sorted as a 1D array) |
| 13 | + * |
| 14 | + * LeetCode: #74 and #240 |
| 15 | + */ |
| 16 | +public class Search2DMatrix { |
| 17 | + |
| 18 | + /** |
| 19 | + * Variation 1: Search in a matrix where each row and each column is sorted |
| 20 | + * Time: O(m + n) |
| 21 | + * |
| 22 | + * @param matrix input matrix |
| 23 | + * @param target value to find |
| 24 | + * @return true if found, false otherwise |
| 25 | + */ |
| 26 | + public static boolean searchMatrixSortedRowsAndCols(int[][] matrix, int target) { |
| 27 | + int rows = matrix.length; |
| 28 | + if (rows == 0) return false; |
| 29 | + |
| 30 | + int cols = matrix[0].length; |
| 31 | + int row = 0, col = cols - 1; |
| 32 | + |
| 33 | + while (row < rows && col >= 0) { |
| 34 | + int val = matrix[row][col]; |
| 35 | + if (val == target) return true; |
| 36 | + else if (val > target) col--; |
| 37 | + else row++; |
| 38 | + } |
| 39 | + |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Variation 2: Search in a matrix that behaves like a flattened sorted array |
| 45 | + * Time: O(log(m * n)) |
| 46 | + * |
| 47 | + * @param matrix input matrix |
| 48 | + * @param target value to find |
| 49 | + * @return true if found, false otherwise |
| 50 | + */ |
| 51 | + public static boolean searchMatrixFlattenedSorted(int[][] matrix, int target) { |
| 52 | + int rows = matrix.length; |
| 53 | + if (rows == 0) return false; |
| 54 | + |
| 55 | + int cols = matrix[0].length; |
| 56 | + int left = 0, right = rows * cols - 1; |
| 57 | + |
| 58 | + while (left <= right) { |
| 59 | + int mid = left + (right - left) / 2; |
| 60 | + int val = matrix[mid / cols][mid % cols]; |
| 61 | + |
| 62 | + if (val == target) return true; |
| 63 | + else if (val < target) left = mid + 1; |
| 64 | + else right = mid - 1; |
| 65 | + } |
| 66 | + |
| 67 | + return false; |
| 68 | + } |
| 69 | + |
| 70 | + // Example usage |
| 71 | + public static void main(String[] args) { |
| 72 | + int[][] matrix1 = { |
| 73 | + {1, 4, 7, 11}, |
| 74 | + {2, 5, 8, 12}, |
| 75 | + {3, 6, 9, 16}, |
| 76 | + {10, 13, 14, 17} |
| 77 | + }; |
| 78 | + System.out.println(searchMatrixSortedRowsAndCols(matrix1, 5)); // true |
| 79 | + |
| 80 | + int[][] matrix2 = { |
| 81 | + {1, 3, 5, 7}, |
| 82 | + {10, 11, 16, 20}, |
| 83 | + {23, 30, 34, 50} |
| 84 | + }; |
| 85 | + System.out.println(searchMatrixFlattenedSorted(matrix2, 3)); // true |
| 86 | + } |
| 87 | +} |
0 commit comments