-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find kth element of Spiral Matrix.java
79 lines (76 loc) · 1.66 KB
/
Find kth element of Spiral Matrix.java
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
//{ Driver Code Starts
import java.util.*;
class Find_Given_Element_Of_Spiral_Matrix
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t > 0)
{
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int arr[][] = new int[1000][1000];
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++ )
{
arr[i][j] = sc.nextInt();
}
}
System.out.println(new Solution().findK(arr, n, m, k));
t--;
}
}
}
// } Driver Code Ends
class Solution
{
/*You are required to complete this method*/
int findK(int A[][], int n, int m, int k)
{
// Your code here
int top=0,left=0;
int bottom=n-1;
int right=m-1;
while(left<=right && top<=bottom)
{
for(int i=left;i<=right;i++)
{
k--;
if(k==0)
return A[top][i];
}
top++;
for(int i=top;i<=bottom;i++)
{
k--;
if(k==0)
return A[i][right];
}
right--;
if(top<=bottom)
{
for(int i=right;i>=left;i--)
{
k--;
if(k==0)
return A[bottom][i];
}
bottom--;
}
if(left<=right)
{
for(int i=bottom;i>=top;i--)
{
k--;
if(k==0)
return A[i][left];
}
left++;
}
}
return 0;
}
}