Skip to content

Commit 35f3259

Browse files
committed
Add Search a 2D Matrix algorithm
1 parent 1c6026e commit 35f3259

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
}

0 commit comments

Comments
 (0)