spiral Matrix II

螺旋矩阵

题目

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

Example:

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

解析重点

1.这可以看作一道数学找规律的题目,上,右,下,左是为循环一圈,坐标循环一圈时有规律的变化。上时横坐标不变,
纵坐标不断增加,到最右边终止上边的循环,横坐标+1.其他位置依此类推。
2.终止条件,中心时终止,即左<=右时终止。

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
class Solution {
public static int[][] generateMatrix(int n) {
int[][] ret = new int[n][n];
int left = 0,top = 0;
int right = n -1,down = n - 1;
int count = 1;
while (left <= right) {
for (int j = left; j <= right; j ++) {
ret[top][j] = count++;
}
top ++;
for (int i = top; i <= down; i ++) {
ret[i][right] = count ++;
}
right --;
for (int j = right; j >= left; j --) {
ret[down][j] = count ++;
}
down --;
for (int i = down; i >= top; i --) {
ret[i][left] = count ++;
}
left ++;
}
return ret;
}
}
undefined