-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch in a 2-D matrix
36 lines (31 loc) · 1.02 KB
/
Search in a 2-D matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.*;
import java.util.*;
public class Solution {
public static boolean searchMatrix(int[][] matrix, int target) {
int i = 0, j = matrix[0].length - 1;
while (i < matrix.length && j >= 0) {
if (matrix[i][j] == target) {
return true;
} else if (matrix[i][j] > target) {
j--;
} else {
i++;
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int mat[][] = new int[n][m];
for(int i = 0 ; i < mat.length ; i++){
for(int j = 0 ; j < mat[0].length ; j++){
mat[i][j] = sc.nextInt();
}
}
int x = sc.nextInt();
boolean res = searchMatrix(mat,x);
System.out.println(res);
}
}