题目链接
思路:
此题的思路与54题一致。54题为转圈打印,此题为转圈填充数组。
使用54题的思路,转圈的过程中对数字num自增并填充
public int[][] generateMatrix(int n) {
if (n == 1) {
return new int[][]{{1}};
}
int[][] ans = new int[n][n];
int tR = 0;
int tC = 0;
int dR = n - 1;
int dC = n - 1;
int num = 0;
while (tR <= dR && tC <= dC) {
if (tR == dR) { // 当前圈只有一行
for (int i = tC; i <= dC; i++) {
ans[tR][i] = ++num;
}
} else if (tC == dC) { // 当前圈只有一列
for (int i = tR; i <= dR; i++) {
ans[i][tC] = ++num;
}
} else {
int curR = tR;
int curC = tC;
while (curC != dC) { // 当前圈最上边的一行
ans[tR][curC] = ++num;
curC++;
}
while (curR != dR) { // 当前圈最右边的一列
ans[curR][dC] = ++num;
curR++;
}
while (curC != tC) { // 当前圈最下面的一行
ans[dR][curC] = ++num;
curC--;
}
while (curR != tR) { // 当前圈最左边的一列
ans[curR][tC] = ++num;
curR--;
}
}
tR++;
tC++;
dR--;
dC--;
}
return ans;
}