File tree Expand file tree Collapse file tree
src/main/java/com/thealgorithms/matrix Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .thealgorithms .matrix ;
2+
3+ /**
4+ * Search a 2D Matrix
5+ * Each row is sorted left to right, and the first element of each row
6+ * is greater than the last element of the previous row.
7+ *
8+ * Time Complexity: O(log(m*n))
9+ * Space Complexity: O(1)
10+ */
11+ public class Search2DMatrix {
12+
13+ /**
14+ * Searches for a target value in a 2D matrix using binary search.
15+ *
16+ * @param matrix the 2D matrix
17+ * @param target the value to search
18+ * @return true if found, false otherwise
19+ */
20+ public static boolean searchMatrix (int [][] matrix , int target ) {
21+ if (matrix == null || matrix .length == 0 || matrix [0 ].length == 0 ) {
22+ return false ;
23+ }
24+
25+ int rows = matrix .length ;
26+ int cols = matrix [0 ].length ;
27+
28+ int left = 0 ;
29+ int right = rows * cols - 1 ;
30+
31+ while (left <= right ) {
32+ int mid = (left + right ) / 2 ;
33+
34+ int midValue = matrix [mid / cols ][mid % cols ];
35+
36+ if (midValue == target ) {
37+ return true ;
38+ } else if (midValue < target ) {
39+ left = mid + 1 ;
40+ } else {
41+ right = mid - 1 ;
42+ }
43+ }
44+
45+ return false ;
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments