考验编程技巧,下面的写法相对比较好懂好记忆。基本思路就是定义四个边界的范围,围绕矩阵四周上下左右逐行逐列输出,同时更新上下左右的行列坐标的值即可。python和C++两种语言实现。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int count = 1;
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
while (true) {
// fill top row
for (int i = left; i <= right; i++) {
res[top][i] = count++;
}
top++;
if (top > bottom) {
break;
}
// fill right col
for (int j = top; j <= bottom; j++) {
res[j][right] = count++;
}
right--;
if (right < left) {
break;
}
// fill bottom row
for (int k = right; k >= left; k--) {
res[bottom][k] = count++;
}
bottom--;
if (bottom < top) {
break;
}
// fill left col
for (int l = bottom; l >= top; l--) {
res[l][left] = count++;
}
left++;
if (left > right) {
break;
}
}
return res;
}
};
class Solution(object):
def generateMatrix(self, n):
res = [[0] * n for _ in range(n)]
count = 1
top = 0
bottom = n - 1
left = 0
right = n - 1
while (True):
for i in range(left, right + 1):
res[top][i] = count
count += 1
top += 1
if (top > bottom):
break
for j in range(top, bottom + 1):
res[j][right] = count
count += 1
right -= 1
if (right < left):
break
for k in range(right, left - 1, -1):
res[bottom][k] = count
count += 1
bottom -= 1
if (bottom < top):
break
for l in range(bottom, top - 1, -1):
res[l][left] = count
count += 1
left += 1
if (left > right):
break
return res