给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1 输出:[[1]]
提示:
1 <= n <= 20
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
res = [[0] * n for _ in range(n)]
num = 1
m1, m2 = 0, n - 1
while m1 < m2:
for j in range(m1, m2):
res[m1][j] = num
num += 1
for i in range(m1, m2):
res[i][m2] = num
num += 1
for j in range(m2, m1, -1):
res[m2][j] = num
num += 1
for i in range(m2, m1, -1):
res[i][m1] = num
num += 1
m1 += 1
m2 -= 1
if m1 == m2:
res[m1][m1] = num
return res
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int num = 1;
int m1 = 0, m2 = n - 1;
while (m1 < m2) {
for (int j = m1; j < m2; ++j) {
res[m1][j] = num++;
}
for (int i = m1; i < m2; ++i) {
res[i][m2] = num++;
}
for (int j = m2; j > m1; --j) {
res[m2][j] = num++;
}
for (int i = m2; i > m1; --i) {
res[i][m1] = num++;
}
++m1;
--m2;
}
if (m1 == m2) {
res[m1][m1] = num;
}
return res;
}
}
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int num = 1;
int m1 = 0, m2 = n - 1;
while (m1 < m2) {
for (int j = m1; j < m2; ++j) {
res[m1][j] = num++;
}
for (int i = m1; i < m2; ++i) {
res[i][m2] = num++;
}
for (int j = m2; j > m1; --j) {
res[m2][j] = num++;
}
for (int i = m2; i > m1; --i) {
res[i][m1] = num++;
}
++m1;
--m2;
}
if (m1 == m2) {
res[m1][m1] = num;
}
return res;
}
};