题目:给定一个正整数n,生成一个包含1到 n^2 的所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
例子:
输入:3
输出:[[1,2,3],[8,9,4],[7,6,5]]
解题思路:这里使用二维数组,按照螺旋排列顺序插入正整数,排列方向共有4个,分别是从左上到右上、从右上到右下、从右下到左下、从左下到左上,这里需要注意方向变化时,数组下标的处理方式
解题流程:
代码如下所示:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n][n];
memset(arr, 0, sizeof(int) * n * n);
int i = 0;
int j = 0;
int count = 0;
int path = 1;
while(count < n * n) {
switch (path)
{
case 1: // LeftTop to RightTop
count++;
arr[i][j] = count;
if(count < n * n) {
if((j + 1 < n) && (arr[i][j+1] == 0)) {
j++;
path = 1;
}
else {
i++;
path = 2;
}
}
break;
case 2: // RightTop to RightDown
count++;
arr[i][j] = count;
if(count < n * n) {
if((i + 1 < n) && (arr[i+1][j] == 0)) {
i++;
path = 2;
}
else {
j--;
path = 3;
}
}
break;
case 3: // RightDown to LeftDown
count++;
arr[i][j] = count;
if(count < n * n) {
if((j - 1 >= 0) && (arr[i][j-1] == 0)) {
j--;
path = 3;
}
else {
i--;
path = 4;
}
}
break;
case 4: // LeftDown to LeftTop
count++;
arr[i][j] = count;
if(count < n * n) {
if((i - 1 >= 0) && (arr[i-1][j] == 0)) {
i--;
path = 4;
}
else {
j++;
path = 1;
}
}
break;
}
}
cout << "[" ;
for(int c = 0; c < n; c++) {
cout << "[" ;
for(int d = 0; d < n; d++) {
if(d < n - 1) {
cout << arr[c][d] << ",";
}
else {
cout << arr[c][d];
}
}
if(c < n - 1) {
cout << "],";
}
else {
cout << "]";
}
}
cout << "]" << endl;
return 0;
}