Description
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Examples
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
代码
没啥好说的……蛇形填数,注意顺序就行
class Solution {
public int[][] generateMatrix(int n) {
int[][] answer = new int[n][n];
int count = 1;
int i, j;
i = 0;
j = 0;
while(count <= n * n){
while((j < n) && (answer[i][j] == 0)){
answer[i][j] = count;
j++;
count++;
}
j--;
i++;
while((i < n) && (answer[i][j] == 0)){
answer[i][j] = count;
i++;
count++;
}
j--;
i--;
while((j >= 0) && (answer[i][j] == 0)){
answer[i][j] = count;
j--;
count++;
}
i--;
j++;
while((i >= 0) && (answer[i][j] == 0)){
answer[i][j] = count;
i--;
count++;
}
i++;
j++;
}
return answer;
}
}