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 ] ]
Solution:
这道题和那道:LeetCode 54 _ Sprial Matrix 旋转矩阵 是一样的,思路也完全相似,就不赘述了。
有一点相比于LC54中写的可以优化的是,由于这次输入的col和row相同,我们可以直接通过已经输出的字符数直接判断是否输入完成,这样就不用在每回第三、四次转向的时候继续判断是否越界了。
Code:
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
if (n == 0) {
return res;
}
int count = 1;
int rowS = 0, rowE = n - 1;
int colS = 0, colE = n - 1;
while (count <= n * n) {
for (int i = colS; i <= colE; i++) {
res[rowS][i] = count;
count++;
}
rowS++;
for (int i = rowS; i <= rowE; i++) {
res[i][colE] = count;
count++;
}
colE--;
for (int i = colE; i >= colS; i--) {
res[rowE][i] = count;
count++;
}
rowE--;
for (int i = rowE; i >= rowS; i--) {
res[i][colS] = count;
count++;
}
colS++;
}
return res;
}
提交情况:
第一次啊!一次提交100%!纪念一下: