-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind kth element of spiral matrix.cpp
93 lines (85 loc) · 1.93 KB
/
Find kth element of spiral matrix.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
// } Driver Code Ends
class Solution
{
public:
/*You are required to complete this method*/
int findK(int a[MAX][MAX], int n, int m, int k)
{
int top = 0, bottom = n - 1, left = 0, right = m - 1;
while (top <= bottom && left <= right)
{
for (int i = left; i <= right; i++) // for top
{
k--;
if (k == 0)
{
return a[top][i];
}
}
top++;
for (int i = top; i <= bottom; i++) // for right
{
k--;
if (k == 0)
{
return a[i][right];
}
}
right--;
// for bottom
if (top <= bottom)
{
for (int i = right; i >= left; i--)
{
k--;
if (k == 0)
{
return a[bottom][i];
}
}
bottom--;
}
// for left
if (left <= right)
{
for (int i = bottom; i >= top; i--)
{
k--;
if (k == 0)
{
return a[i][left];
}
}
left++;
}
}
}
};
//{ Driver Code Starts.
int main()
{
int T;
cin >> T;
while (T--)
{
int n, m;
int k = 0;
// cin>>k;
cin >> n >> m >> k;
int a[MAX][MAX];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
Solution ob;
cout << ob.findK(a, n, m, k) << endl;
}
}
// } Driver Code Ends