您的位置:首页 > 其它

蛇形矩阵求解

2016-09-01 22:07 183 查看
先放代码:

#include<iostream>
using namespace std;

int main()
{
int n;
cin>>n;
int **a=new int*
;
for(int i=0;i<n;i++)
a[i]=new int
;
for(int i=0;i<n;i++)
a[0][i]=i+1;
int count=n+1;
bool s=true;
int step=n-1;
int sx=1,sy=n-1;
while(step>0&&count<n*n)
{
if(s)
{
int step1=step;
while(step1--)
{
a[sx++][sy]=count++;
}
sy--;
sx--;
//count--;
step1=step;
while(step1--)
{
a[sx][sy--]=count++;
}
//count--;
sx--;
sy++;
step--;
s=false;
}
else
{
int step1=step;
//sy++;
while(step1--)
{
a[sx--][sy]=count++;
}
sx++;
sy++;
step1=step;
while(step1--)
{
a[sx][sy++]=count++;
}
sy--;
sx++;
step--;
s=true;
}
}

for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cout<<a[i][j]<<" ";
return 0;
}

       所谓蛇形矩阵,就是矩阵赋值的规则定义,所以规则摆明,程序也就自然而然写出来。没什么特别要说的,代码编写就是先要有思想,然后按照自己的思想写代码。大牛代码质量高,但一般人写出来的代码一定是还要调试。思想是第一步,实现是第二步,调试是第三步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息