-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateSpiral.java
More file actions
43 lines (35 loc) · 1.31 KB
/
GenerateSpiral.java
File metadata and controls
43 lines (35 loc) · 1.31 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
package ArraysD2;
public class GenerateSpiral {
static int[][] generateSpiralMatrix(int n) {
int[][] matrix = new int[n][n];
int topRow = 0, bottomRow = n - 1, leftCol = 0, rightCol = n - 1;
int totalElements = 1;
while (totalElements <= n * n) {
// topRow -> leftCol to rightCol
for (int j = leftCol; j <= rightCol && totalElements <= n * n; j++) {
matrix[topRow][j] = totalElements;
totalElements++;
}
topRow++;
// rightCol -> topRow to bottomRow
for (int i = topRow; i <= bottomRow && totalElements <= n * n; i++) {
matrix[i][rightCol] = totalElements;
totalElements++;
}
rightCol--;
// bottomRow -> rightCol to leftCol
for (int j = rightCol; j >= leftCol && totalElements <= n * n; j--) {
matrix[bottomRow][j] = totalElements;
totalElements++;
}
bottomRow--;
// leftCol -> bottomRow to topRow
for (int i = bottomRow; i >= topRow && totalElements <= n * n; i--) {
matrix[i][leftCol] = totalElements;
totalElements++;
}
leftCol++;
}
return matrix;
}
}