Problem Description:
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 ] ]
Analysis:
本题和54. Spiral Matrix思路一致,就是找到一个方法螺旋遍历这个矩阵,然后依次给矩阵中的元素赋值。代码如下:
Code:
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int s = 0, t = 0;
int row = n - 1, col = n - 1;
int cnt = 1;
while(s <= row && t <= col) {
for(int i = t; i <= col; i++) {
res[s][i] = cnt++;
}
s++;
for(int i = s; i <= row; i++) {
res[i][col] = cnt++;
}
col--;
for(int i = col; i>=t; i--) {
res[row][i] = cnt++;
}
row--;
for(int i = row; i>=s; i--) {
res[i][t] = cnt++;
}
t++;
}
return res;
}
}