-
Notifications
You must be signed in to change notification settings - Fork 0
/
59. Spiral Matrix II.java
45 lines (36 loc) · 1.18 KB
/
59. Spiral Matrix II.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
/*
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
*/
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int cnt = 1;
for (int layer = 0; layer < (n + 1) / 2; layer++) {
// direction 1 - traverse from left to right
for (int ptr = layer; ptr < n - layer; ptr++) {
result[layer][ptr] = cnt++;
}
// direction 2 - traverse from top to bottom
for (int ptr = layer + 1; ptr < n - layer; ptr++) {
result[ptr][n - layer - 1] = cnt++;
}
// direction 3 - traverse from right to left
for (int ptr = layer + 1; ptr < n - layer; ptr++) {
result[n - layer - 1][n - ptr - 1] = cnt++;
}
// direction 4 - traverse from bottom to top
for (int ptr = layer + 1; ptr < n - layer - 1; ptr++) {
result[n - ptr - 1][layer] = cnt++;
}
}
return result;
}
}