-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path13_matrix_search.cpp
80 lines (63 loc) · 2.23 KB
/
13_matrix_search.cpp
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Problem Name: Matrix Search
Given an n x m matrix, where every row and column is sorted in increasing order, and a number x .
Find if element x is present in the matrix or not.
Input Format: First line consists of two space separated integers N and M,
denoting the number of element in a row and column respectively.
Second line of each test case consists of N*M space separated integers
denoting the elements in the matrix in row major order.
Third line of each test case contains a single integer x, the element to be searched.
Constraints: 1 <= N,
M <= 30
0 <= A[i] <= 100
Output Format: Print 1 if the element is present in the matrix, else 0.
Sample Input: 3 3
3 30 38
44 52 54
57 60 69
62
Sample Output: 0
Explanation: Search the element in the sorted matrix.
If the element is present print 1 otherwise print 0.
In the sample input,in first case 62 is not present in the matrix so 0 is printed.
Similarly, for second case 55 is present in the matrix so 1 is printed.
*/
#include <iostream>
using namespace std;
// using Staircase Search Approach
int searchMatrix(int **arr, int rows, int cols, int key){
int rowStart = 0;
int colEnd = cols-1;
while(rowStart <= rows-1 && colEnd >= 0){
if(key == arr[rowStart][colEnd]){
return 1;
}else if(key < arr[rowStart][colEnd]){
colEnd--;
}else{
rowStart++;
}
}
return 0;
}
int main() {
int rows, cols;
cout << "Enter Matrix [Rows x Cols]: ";
cin >> rows >> cols;
int **arr = new int*[rows];
for(int row=0; row<=rows; row++){
arr[row] = new int[cols];
}
cout << "Enter Matrix elements: \n";
for(int row=0; row<=rows-1; row++){
for(int col=0; col<=cols-1; col++){
cin >> arr[row][col];
}
}
int key;
cout << "Enter Search Key: ";
cin >> key;
// Search Matrix
cout << "Output: " << searchMatrix(arr, rows, cols, key);
cout << endl;
return 0;
}