Skip to content

Commit 2642638

Browse files
Merge pull request #558 from Ojasvix20/feat/hacktober/Seach2DMatrix
Added search 2D matrix algorithm for hacktober fest
2 parents fe18b58 + 341efd7 commit 2642638

1 file changed

Lines changed: 91 additions & 0 deletions

File tree

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/*
2+
* Algorithm Name: Search a 2D Matrix
3+
* Programming Language: Java
4+
* Category: Matrix, Binary Search
5+
* Difficulty Level: Medium
6+
*
7+
* Author: Ojasvi Bakshi
8+
*
9+
* Algorithm Description:
10+
* Efficiently searches for a value in an m x n matrix where each row is sorted
11+
* left to right, and the first element of each row is greater than the last
12+
* element of the previous row. This implementation uses binary search.
13+
*
14+
* Time Complexity: O(log(m*n))
15+
* Space Complexity: O(1)
16+
*/
17+
// package DSA_Code.Java.algorithms.matrix;
18+
19+
import java.util.Scanner;
20+
import java.util.Arrays;
21+
22+
public class Search2DMatrix {
23+
24+
public static boolean searchMatrix(int[][] matrix, int target) {
25+
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
26+
return false;
27+
}
28+
29+
int m = matrix.length;
30+
int n = matrix[0].length;
31+
32+
int left = 0;
33+
int right = m * n - 1; // Treat the matrix as a flattened 1D array
34+
35+
while (left <= right) {
36+
int mid = left + (right - left) / 2;
37+
38+
// Convert the 1D mid-point back to 2D coordinates
39+
int midRow = mid / n;
40+
int midCol = mid % n;
41+
int midValue = matrix[midRow][midCol];
42+
43+
if (midValue == target) {
44+
return true;
45+
} else if (midValue < target) {
46+
left = mid + 1;
47+
} else {
48+
right = mid - 1;
49+
}
50+
}
51+
52+
return false;
53+
}
54+
55+
public static void main(String[] args) {
56+
Scanner sc = new Scanner(System.in);
57+
58+
System.out.print("Enter number of rows: ");
59+
int m = sc.nextInt();
60+
System.out.print("Enter number of columns: ");
61+
int n = sc.nextInt();
62+
63+
int[][] matrix = new int[m][n];
64+
65+
System.out.println("Enter sorted matrix elements:");
66+
for (int i = 0; i < m; i++) {
67+
for (int j = 0; j < n; j++) {
68+
matrix[i][j] = sc.nextInt();
69+
}
70+
}
71+
72+
System.out.print("\nEnter the target value to search for: ");
73+
int target = sc.nextInt();
74+
75+
System.out.println("\nOriginal Matrix:");
76+
for (int[] row : matrix) {
77+
System.out.println(Arrays.toString(row));
78+
}
79+
80+
// Apply the algorithm
81+
boolean found = searchMatrix(matrix, target);
82+
83+
if (found) {
84+
System.out.println("\nTarget " + target + " was found in the matrix. ✅");
85+
} else {
86+
System.out.println("\nTarget " + target + " was not found in the matrix. ❌");
87+
}
88+
89+
sc.close();
90+
}
91+
}

0 commit comments

Comments
 (0)