-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch_sorted_2d.cpp
More file actions
88 lines (69 loc) · 1.49 KB
/
Copy pathsearch_sorted_2d.cpp
File metadata and controls
88 lines (69 loc) · 1.49 KB
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
80
81
82
83
84
85
86
87
88
/*
Question : https://youtu.be/N1RyGhXJ7Zc?list=PL-Jc9J83PIiFj7YSPl2ulcpwy-mwj1SSk
Search in a sorted 2d array , all rows and cols will be sorted
Solution : https://youtu.be/5vP0-g94xEA?list=PL-Jc9J83PIiFj7YSPl2ulcpwy-mwj1SSk
*/
#include <iostream>
#include<algorithm>
#include <vector>
using namespace std;
vector<vector<int> > input()
{
// takes input in a 2d vector and return a 2d vector
int r;
cin >>r;
int c=r;
vector<vector<int> > arr(r, vector<int>(c, 0));
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
cin >> arr[i][j];
}
return arr;
}
void printMatrix(vector<vector<int> > &arr1)
{
int r1 = arr1.size();
int c1 = arr1[0].size();
for (int i = 0; i < r1; i++)
{
for (int j = 0; j < c1; j++)
cout << arr1[i][j] << " ";
cout << "\n";
}
}
void search(vector<vector<int> > &arr,int key)
{
int r = arr.size();
int c = arr[0].size();
int i=0 , j=c-1;
int flag=0;//to denote found or not
while(i<r && j>=0)
{
if(key==arr[i][j])
{
cout<<i<<"\n"<<j<<"\n";
flag=1;
break;
}
else if(key>arr[i][j])
{
i++;
}
else
{
j--;
}
}
if(!flag)
cout<<"Not Found\n";
}
int main()
{
vector<vector<int> > arr = input();
int key;
cin>>key;
// cout << "Original input : \n";
// printMatrix(arr);
search(arr,key);
}