67 lines
2.3 KiB
Java
67 lines
2.3 KiB
Java
package com.dsa.binarysearch;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.FileReader;
|
|
import java.io.IOException;
|
|
import java.util.Arrays;
|
|
|
|
public class SearchIn2DMatrix {
|
|
public static void main(String[] args) {
|
|
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
|
|
int rows = Integer.parseInt(reader.readLine().trim());
|
|
int[][] matrix = new int[rows][];
|
|
for (int i = 0; i < rows; i++) {
|
|
String[] line = reader.readLine().split(",");
|
|
matrix[i] = new int[line.length];
|
|
for (int j = 0; j < line.length; j++) {
|
|
matrix[i][j] = Integer.parseInt(line[j].trim());
|
|
}
|
|
}
|
|
int target = Integer.parseInt(reader.readLine().trim());
|
|
var solution = new SearchIn2DMatrix();
|
|
System.out.println("Matrix:");
|
|
for (int[] row : matrix) {
|
|
System.out.println(Arrays.toString(row));
|
|
}
|
|
System.out.println("Target to Search: " + target);
|
|
// System.out.println("Is Target Present: " + solution.searchMatrix(matrix, target));
|
|
System.out.println("Is Target Present: " + solution.searchInRowAndColumnWiseSortedMatrix(matrix, target));
|
|
} catch (IOException ioe) {
|
|
throw new RuntimeException(ioe);
|
|
}
|
|
}
|
|
|
|
public boolean searchMatrix(int[][] matrix, int target) {
|
|
int left = 0;
|
|
int right = matrix.length * matrix[0].length - 1;
|
|
while (left <= right) {
|
|
int mid = (left + right) / 2;
|
|
int row = mid/matrix[0].length;
|
|
int col = mid % matrix[0].length;
|
|
if (matrix[row][col] == target) {
|
|
return true;
|
|
} else if (matrix[row][col] > target) {
|
|
right = mid - 1;
|
|
} else {
|
|
left = mid + 1;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public boolean searchInRowAndColumnWiseSortedMatrix(int[][] matrix, int target) {
|
|
int row = 0;
|
|
int col = matrix[0].length - 1;
|
|
while (row < matrix.length && col >= 0) {
|
|
if (matrix[row][col] < target) {
|
|
row++;
|
|
} else if (matrix[row][col] > target) {
|
|
col--;
|
|
} else {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|