-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSearch_In_Matrix.cpp
More file actions
96 lines (85 loc) · 1.91 KB
/
Copy pathSearch_In_Matrix.cpp
File metadata and controls
96 lines (85 loc) · 1.91 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
89
90
91
92
93
94
95
96
//! *************************** Recursive Method ******************************
#include <iostream>
using namespace std;
int m, n, key;
bool search(int *mat, int row, int col)
{
if (row < m && col >= 0)
{
if (key == *(mat + row * n + col))
{
return true;
}
if (key < *(mat + row * n + col))
{
return search(mat, row, --col);
}
if (key > *(mat + row * n + col))
{
return search(mat, ++row, col);
}
}
return false;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
cin >> m >> n >> key;
int mat[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> mat[i][j];
}
}
int row = 0, col = n - 1;
if (search(&mat[0][0], row, col))
cout << "Element found";
else
cout << "Element does not exist.";
return 0;
}
//? *************************** Direct Method ******************************
/* #include <iostream>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int m, n, key;
cin >> m >> n >> key;
int mat[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> mat[i][j];
}
}
int row = 0, col = n - 1;
while (row < m && col >= 0)
{
if (key == mat[row][col])
{
cout << "Element found";
return 0;
}
if (key < mat[row][col])
{
col--;
continue;
}
if (key > mat[row][col])
{
row++;
}
}
cout << "Element does not exist";
return 0;
} */