螺旋矩阵的实现

螺旋矩阵就是形如如下图的矩阵:

看到矩阵知道它由四条边组成,这样的话就有这样的n/2个环,但是如果是奇数矩阵的话在最中间需要特殊处理一下:

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<iomanip>
#include<queue>
#define pi acos(-1)
#define For(i, a, b) for(int (i) = (a); (i) <= (b); (i) ++)
#define Bor(i, a, b) for(int (i) = (b); (i) >= (a); (i) --)
using namespace std;
typedef long long ll;
const int maxn = 100 + 10;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-10;
const ll mod = 1e9 + 7;
inline int read(){
    int ret=0,f=0;char ch=getchar();
    while(ch>'9'||ch<'0') f^=ch=='-',ch=getchar();
    while(ch<='9'&&ch>='0') ret=ret*10+ch-'0',ch=getchar();
    return f?-ret:ret;
}

int n;
int a[maxn][maxn]; 

int main(){
	ios::sync_with_stdio(false);
	cin >> n;
	int t = n/2;
	int i = 0;
	int j = 0;
	int ans = n;
	int st = 1;
	for(int num =0;num < t; num++){
		for(; j < ans - 1; j++)a[i][j] = st++;
		for(; i < ans - 1; i++)a[i][j] = st++;
		for(j = ans -1; j > num; j--)a[i][j] = st ++;
		for(i = ans -1; i > num; i--)a[i][j] = st ++;
		i++,ans--,st -= 1;
	}
	if(n%2!=0)a[i][j+1]=st+1;
	for(i=0;i<n;i++){
	  	for(j=0;j<n;j++)
	   		cout<<setw(3)<<a[i][j];
		cout<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值