-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathNthSpiralElement.java
70 lines (61 loc) · 1.75 KB
/
NthSpiralElement.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
/*https://practice.geeksforgeeks.org/problems/find-nth-element-of-spiral-matrix/1*/
class GfG
{
/*You are required to complete this method*/
int findK(int matrix[][], int n, int m, int k)
{
// Your code here
int rs = 0, re = n-1, cs = 0, ce = m-1;
List<Integer> l = new ArrayList<Integer>();
int i = 0, j = 0;
//till we have more elements
while (rs <= re && cs <= ce && k >= 0)
{
//add the top row
for (j = cs; j <= ce; ++j)
{
if (matrix[i][j] != -1000)
{
if (--k == 0) return matrix[i][j];
matrix[i][j] = -1000;
}
}
//delete top row
++rs; --j;
//add right column
for (i = rs; i <= re; ++i)
{
if (matrix[i][j] != -1000)
{
if (--k == 0) return matrix[i][j];
matrix[i][j] = -1000;
}
}
//delete right column
--ce; --i;
//add bottom row
for (j = ce; j >= cs; --j)
{
if (matrix[i][j] != -1000)
{
if (--k == 0) return matrix[i][j];
matrix[i][j] = -1000;
}
}
//delete bottom row
--re; ++j;
//add left column
for (i = re; i >= rs; --i)
{
if (matrix[i][j] != -1000)
{
if (--k == 0) return matrix[i][j];
matrix[i][j] = -1000;
}
}
//delete left column
++cs; ++i;
}
return -1;
}
}