随便写的 还有待改进
好像可以用递归,这里相对暴力点
螺旋矩阵是指一个呈螺旋状的矩阵,它的数字由第一行开始到右边不断变大,向下变大,向左变大,向上变大,如此循环。
可以先写外层元素,然后里面的数按规律增加,循环打印直到最后
给出一个 3
可以给出以下矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
void generate(int n){
int a[n+2][n+2];
for(int i=0;i<n+2;i++){
for(int j=0;j<n+2;j++){
if(i==n+1||j==n+1||i==0||j==0){
a[i][j]=-1;
}else{
a[i][j]=0;
}
}
}
int ope=0;//操作
int indexi=1;
int indexj=1;
int count=n*n;//总数
int mm=0;
while(count>0){
while(ope==0&&a[indexi][indexj]==0){
a[indexi][indexj]=++mm;
printf("%d\n",a[indexi][indexj]);
indexj++;
count--;
}
ope++;
indexj--;
indexi++;
while(ope==1&&a[indexi][indexj]==0){
a[indexi][indexj]=++mm;
indexi++;
count--;
}
ope++;
indexi--;
indexj--;
while(ope==2&&a[indexi][indexj]==0){
a[indexi][indexj]=++mm;
indexj--;
count--;
}
ope++;
indexj++;
indexi--;
while(ope==3&&a[indexi][indexj]!=-1&&a[indexi][indexj]==0){
a[indexi][indexj]=++mm;
indexi--;
count--;
}
indexi++;
indexj++;
ope=0;
}
for(int i=1;i<n+1;i++){
for(int j=1;j<n+1;j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
int main() {
generate(4);
}