我有一个程序,我必须用从1到n的螺旋形式来填充矩阵a。然而,我的程序只填充矩阵的边框。我的问题是如何优化算法,使其填充整个二维数组。
#include <iostream>
using namespace std;
void print();
const int n=9;
int a[n][n];
int main()
{
int counter=1,j=0,i=0;
for(int i=0; i<n; i++)
{
a[i][j]=counter;
counter++;
}
counter--;
for(int k=0; k<n; k++)
{
a[n-1][k]=counter;
counter++;
}
counter--;
for(int i=n-1; i>=0; i--)
{
a[i][n-1]=counter;
counter++;
}
counter--;
for(int j=n-1; j>0; j--)
{
a[i][j]=counter;
counter++;
}
print();
return 0;
}
void print ()
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout<<a[i][j]<<'\t';
}
cout<<endl;
}
}
发布于 2018-01-31 09:57:55
有几件事需要在推特上发布:
m
,它被简化为零)。int i
和int j
,但在循环中使用for (int i=0;...)
,这意味着您没有使用以前定义的整数的值。最后这看起来是这样的:
#include <iostream>
using namespace std;
void print();
const int n=6;
int a[n][n];
int main()
{
int counter = 1;
for (int m = n; m > 0; m--)
{
int j=n-m,i=0;
for(i=n-m; i<m; i++)
{
a[i][j]=counter;
counter++;
}
counter--;
for(int k=n-m; k<m; k++)
{
a[m-1][k]=counter;
counter++;
}
counter--;
for(i=m-1; i>=n-m; i--)
{
a[i][m-1]=counter;
counter++;
}
counter--;
for(j=m-1; j>n-m; j--)
{
a[n-m][j]=counter;
counter++;
}
}
print();
return 0;
}
使用您的print()
,这将产生以下结果:
1 20 19 18 17 16
2 21 32 31 30 15
3 22 33 36 29 14
4 23 34 35 28 13
5 24 25 26 27 12
6 7 8 9 10 11
注意,我在这里选择了n=6
。
https://stackoverflow.com/questions/48548063
复制相似问题