用C++实现,给你一个正整数 n ,生成一个包含 1 到 n*n 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 示例 1: 输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
时间: 2023-02-07 09:20:56 浏览: 106
下面是用 C 语言实现的程序:
```
#include <stdio.h>
#include <stdlib.h>
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
int **matrix = (int**)malloc(sizeof(int*)*n);
*returnColumnSizes = (int*)malloc(sizeof(int)*n);
*returnSize = n;
for (int i = 0; i < n; i++) {
matrix[i] = (int*)malloc(sizeof(int)*n);
(*returnColumnSizes)[i] = n;
}
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int num = 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) matrix[top][i] = num++;
top++;
for (int i = top; i <= bottom; i++) matrix[i][right] = num++;
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) matrix[bottom][i] = num++;
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) matrix[i][left] = num++;
left++;
}
}
return matrix;
}
int main() {
int n = 3;
int returnSize, *returnColumnSizes;
int **matrix = generateMatrix(n, &returnSize, &returnColumnSizes);
for (int i = 0; i < returnSize; i++) {
for (int j = 0; j < returnColumnSizes[i]; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果为:
```
1 2 3
8 9 4
7 6 5
```
程序的思路是:初始化一个二维数组 matrix,然后从矩阵的左上角开始,按顺时针的顺序往右、往下、往左、往上四个方向依次填充数字。同时设置四个变量 left、right、top、bottom,表示矩阵的边界。每次循环时把 left、top、right、bottom 分别增加或减少 1,表示每次填充的区域减小 1。
阅读全文