forked from iRupam/NewtonSchoolInfinityJune21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralTraversal.java
More file actions
61 lines (52 loc) · 1.78 KB
/
SpiralTraversal.java
File metadata and controls
61 lines (52 loc) · 1.78 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
package InfinityJune21.TwoDArray;
public class SpiralTraversal {
public static void main(String[] args) {
int n = 5, m = 3;
long arr[][] = new long[n][m];
int element = 1;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
arr[i][j] = element;
element++;
}
}
System.out.println("Array: ");
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
System.out.printf("%3d", arr[i][j]);
}
System.out.println();
}
System.out.println("Spiral Traversal: ");
int rowStart = 0;
int rowEnd = n - 1;
int columnStart = 0;
int columnEnd = m - 1;
while(rowStart <= rowEnd && columnStart <= columnEnd) {
//First Row
for(int column = columnStart; column <= columnEnd; column++) {
System.out.print(arr[rowStart][column] + " ");
}
rowStart++;
//Last Column
for(int row = rowStart; row <= rowEnd; row++) {
System.out.print(arr[row][columnEnd] + " ");
}
columnEnd--;
//Last Row
if(rowStart <= rowEnd) {
for(int column = columnEnd; column >= columnStart; column--) {
System.out.print(arr[rowEnd][column] + " ");
}
rowEnd--;
}
//First Column
if(columnStart <= columnEnd) {
for(int row = rowEnd; row >= rowStart; row--) {
System.out.print(arr[row][columnStart] + " ");
}
columnStart++;
}
}
}
}