用模拟的方式处理蛇形方阵,简单直接
查看原帖
用模拟的方式处理蛇形方阵,简单直接
1347517
just_to_do楼主2025/1/10 11:06

找到规律直接模拟就行

#include<iostream>
#include<iomanip>
using namespace std;
int a[100][100]; 
int main()
{
	int n,cnt=1;
	cin>>n;
	int t=n-1;//t:重复数字的次数 
	for(int i=1;i<=n;i++)//第一行只重复了一次单独处理
	{
		a[1][i]=cnt;
		cnt++;	
	}
	int x=1,y=n;//第一行结束后的坐标位置
	while(cnt<n*n)//
	{
    //规律
		for(int j=1;j<=t;j++)
		{
			x++;
			a[x][y]=cnt;
			cnt++;
		}
		for(int j=1;j<=t;j++)
		{
			y--;
			a[x][y]=cnt;
			cnt++;
		}
		t--;
		for(int j=1;j<=t;j++)
		{
			x--;
			a[x][y]=cnt;
			cnt++;
		}
		for(int j=1;j<=t;j++)
		{
			y++;
			a[x][y]=cnt;
			cnt++;
		}
		t--;
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cout<<setw(3)<<a[i][j];
		}
		cout<<endl;
	}
	return 0;
}
2025/1/10 11:06
加载中...