-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintSpiral.java
More file actions
44 lines (35 loc) · 1.32 KB
/
PrintSpiral.java
File metadata and controls
44 lines (35 loc) · 1.32 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
package ArraysD2;
public class PrintSpiral {
static void printSpiralOrder(int[][] matrix, int r, int c) {
int topRow = 0, bottomRow = r - 1, leftCol = 0, rightCol = c - 1;
int totalElements = 0;
while (totalElements < r * c) {
// topRow -> leftCol to rightCol
for (int j = leftCol; j <= rightCol && totalElements < r * c; j++) {
System.out.println(matrix[topRow][j]);
totalElements++;
}
topRow++;
// rightCol -> topRow to bottomRow
for (int i = topRow; i <= bottomRow && totalElements < r * c; i++) {
System.out.println(matrix[i][rightCol]);
totalElements++;
}
rightCol--;
// bottomRow -> rightCol to leftCol
for (int j = rightCol; j >= leftCol && totalElements < r * c; j--) {
System.out.println(matrix[bottomRow][j]);
totalElements++;
}
bottomRow--;
// leftCol -> bottomRow to topRow
for (int i = bottomRow; i >= topRow && totalElements < r * c; i--) {
System.err.println(matrix[i][leftCol]);
totalElements++;
}
leftCol++;
}
}
public static void main(String[] args) {
}
}