蛇形填数(看准方向,循环)

 打印如下形式的矩阵;
n=5:
1   2   9 10 25
4   3   8 11 24
5   6   7 12 23
16 15 14 13 22
17 18 19 20 21

n=6:
1   2   9 10 25 26
4   3   8 11 24 27
5   6   7 12 23 28
16 15 14 13 22 29
17 18 19 20 21 30
36 35 34 33 32 31

 

代码:

#include <iostream>

#include <iomanip>

using namespace std;

#define MAX 20

int a[MAX][MAX];

int N;

 

void display()

{

for (int i=0;i<N;i++)

{

for (int j=0;j<N;j++)

{

cout<<setw(6)<<a[i][j];

}

cout<<endl;

}

cout<<endl;

}

 

void main()

{

memset(a,0,sizeof(a));

 

cout<<"input the N "<<endl;

cin>>N;

 

int tot = 1;

int x=0;

int y=0;

 

//a[x][y] = tot++;

 

while (tot<N*N)

{

 

a[x][y++] = tot++;

//cout<<"右移1"<<x<<" "<<y<<endl;

for(;x<y;x++) a[x][y] = tot++;

//cout<<"down"<<x<<" "<<y<<endl;

 

for (;y>0;y--) a[x][y] = tot++;

//cout<<"left"<<x<<" "<<y<<endl;

 

a[x++][y] = tot++;

//cout<<"下移1"<<x<<" "<<y<<endl;

 

for (;y<x;y++) a[x][y] = tot++;

//cout<<"右移"<<x<<" "<<y<<endl;

 

for (;x>0;x--) a[x][y] = tot++;

//cout<<"up"<<x<<" "<<y<<endl;

 

}

 

if (N%2)

{

a[0][N-1] = N*N;

}

 

display();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值