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 ] ]
这种题目找规律。。。就是旋转数据 给每个位置赋值:
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
setValue(res,n,0,1);
return res;
}
public void setValue(int[][] res,int n,int begin,int value) {
int i=begin,j=begin;
res[i][j] = value;
int weight = n-1-begin;
int height = weight;
while (j<weight) {
res[i][++j] = ++value;
}
while (i < height) {
res[++i][j] = ++value;
}
while (j > begin) {
res[i][--j] = ++value;
}
while (i > begin+1) {
res[--i][j] = ++value;
if (i == begin + 1) {
setValue(res, n, ++begin, ++value);
}
}
}