leetcode解题: Spiral Matrix II (59)

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

1
2
3
4
5
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

解法1:

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
public class Solution {
public int[][] generateMatrix(int n) {
int level = (n + 1) / 2;
int[][] res = new int[n][n];
// fill by level
int num = 1;
for (int i = 0; i < level; ++i) {
int lastrow = n - i - 1;
int lastcol = n - i - 1;
// move right
for (int j = i; j <= lastcol; ++j) {
res[i][j] = num;
num++;
}
// move down
for (int j = i + 1; j <= lastrow; ++j) {
res[j][lastcol] = num;
num++;
}
// move left
for (int j = lastcol - 1; j >= i; --j) {
res[lastrow][j] = num;
num++;
}
// move up
for (int j = lastrow - 1; j > i; --j) {
res[j][i] = num;
num++;
}
}
return res;
}
}