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

For example,
Given n = 3,

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

思路

这道题其实没有什么算法上的技术含量。题目需要我们按照蛇形的路线生成一个数组,我们其实可以按照题目的要求,碰到不合适的路径不走即可。比较考验编程能力的就是在边界条件和实现的过程中的技巧。

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
48
49
50
51
52
53
54
55
56
57
public class Solution {
public int[][] generateMatrix(int n) {
// A very good way to assign dynamic-length array
int[][] ans = new int[n][];
for (int i = 0; i < n; i++){
ans[i] = new int[n];
for (int j = 0; j < n; j++){
ans[i][j] = 0;
}
}
int x = 0;
int y = 0;
boolean right = true;
boolean down = false;
boolean up = false;
boolean left = false;
for (int count = 1; count <= n * n; count++){
ans[x][y] = count;
boolean rightblock = y + 1 >= n || ans[x][y+1] > 0;
boolean leftblock = y - 1 < 0 || ans[x][y-1] > 0;
boolean upblock = x - 1 < 0 || ans[x-1][y] > 0;
boolean downblock = x + 1 >= n || ans[x+1][y] > 0;
if(rightblock && leftblock && upblock){
right = up = left = false;
down = true;
}
else if(rightblock && leftblock && downblock){
right = down = left = false;
up = true;
}
else if(rightblock && downblock && upblock){
right = down = up = false;
left = true;
}
else if(leftblock && downblock && upblock){
left = down = up = false;
right = true;
}
if(left){
y--;
}
else if(right){
y++;
}
else if(down){
x++;
}
else if(up){
x--;
}
}
return ans;
}
}