05 August 2008
Given a positive integer n, generate a square matrix filled with elements from 1 to _n_2 in spiral order.
Example:
1
2
3
4
5
6
7
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
这道题根据打印顺序来创建二维数组,和54 Spiral Matrix一样的思路。
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
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
if (n <= 0) {
return result;
}
int rowBegin = 0;
int rowEnd = n - 1;
int colBegin = 0;
int colEnd = n - 1;
int index = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
//从左到右
for (int i = colBegin; i<= colEnd; i++) {
result[rowBegin][i] = index;
index++;
}
rowBegin++;
//从上到下
for (int i = rowBegin; i <= rowEnd; i++) {
result[i][colEnd] = index;
index++;
}
colEnd--;
//从右到左
if (colEnd >= colBegin) {
for (int i = colEnd; i >= colBegin; i--) {
result[rowEnd][i] = index;
index++;
}
}
rowEnd--;
//从下到上
if (rowEnd >= rowBegin) {
for (int i = rowEnd; i >= rowBegin; i--) {
result[i][colBegin] = index;
index++;
}
}
colBegin++;
}
return result;
}
}