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 ] ]
题解如下:
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int r1 = 0;
int r2 = n - 1;
int c1 = 0;
int c2 = n - 1;
int num = 1;
while(r1 <= r2 && c1 <= c2) {
//up
for(int c = c1;c <= c2;c++) {
matrix[r1][c] = num++;
}
r1++;
//right
for(int r = r1;r <= r2;r++) {
matrix[r][c2] = num++;
}
c2--;
//bottom
for(int c = c2;c >= c1;c--) {
matrix[r2][c] = num++;
}
r2--;
//left
for(int r = r2;r >= r1;r--) {
matrix[r][c1] = num++;
}
c1++;
}
return matrix;
}
}