蛇形矩阵

链接:https://ac.nowcoder.com/acm/problem/22231
来源:牛客网
 

题目描述

给你一个整数n,输出n∗n的蛇形矩阵。

输入描述:

输入一行,包含一个整数n

输出描述:

输出n行,每行包含n个正整数,通过空格分隔。

1<=n<=1000

示例1

输入

复制4

4

输出

复制1 2 6 7 3 5 8 13 4 9 12 14 10 11 15 16

1 2 6 7
3 5 8 13
4 9 12 14
10 11 15 16
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
int main()
{
    int a[101][101],n,i,j,k,flag=1,flag1;
    cin>>n;
    k=1;i=1;j=1;
    int temp=0;
    while(k<=n*(n+1)/2)
    {
    	flag1=flag;
    	//	cout<<flag1<<"$$"<<endl;
    	while((flag1--)&&(i>=1)&&(j>=1))
    	{
    		//cout<<i<<" "<<j<<" "<<k<<endl; 
    	    a[i][j]=k;
			if(temp==1)
			{
				i++;
				j--;
			}	
			else
			{
				i--;
				j++;
			}
			k++;
			
		}
		//cout<<flag1<<"%"<<i<<"%"<<j<<"%"<<k<<endl;
		if(temp==0)
		{
		i++;
		temp=1;	
		}
		else
		{
		j++;
		temp=0;	
		}
		flag++;
	}
	flag=flag-2;
	//cout<<i<<" "<<j<<" "<<temp<<endl;
	if(temp==0)
	{
	i--;
	j++;
	}
	else
	{
		i++;
		j--;
	}
	
	//cout<<i<<" "<<j<<" "<<flag<<" "<<temp<<endl;

	while(k<=n*n)
	{
		flag1=flag;
		//cout<<flag1<<"%%5"<<endl;
		
    	while((flag1--)&&(i<=n)&&(j<=n))
    	{
    		//cout<<flag1<<" "<<i<<" "<<j<<" "<<k<<endl;
    		a[i][j]=k;
    		if(temp==0)
    		{
    			i--;
    			j++;
			}
			else
			{
				i++;
				j--;
			}
			k++;
		}
			//cout<<i<<"%1%"<<j<<endl;
		if(temp==0)
		{
		i+=2;
		j--;
		temp=1;	
		}
		else
		{
		i--;	
		j+=2;
		temp=0;	
		}
		//cout<<i<<"%2%"<<j<<endl;
		flag--;
	}
    for(i=1;i<=n;i++)
    {
    	for(j=1;j<=n;j++)
    	cout<<a[i][j]<<" ";
    	cout<<endl;
	}
	return 0;
	
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值