配列を使用して正方形のスパイラル行列を作成します

コード例:

#include<stdio.h>
int main()
{
    
    
	int num;
	int cnt;
	int top,bottom;
	int i,j;
	int arr[10][10];
	printf("请输入螺旋方阵的行数(1-10):");
	scanf("%d",&num);

	cnt=1;
	top=0;
	bottom=num-1;

	while(cnt<=num*num&&top<=bottom)
	{
    
    
		i=top;
		j=top;

		if(top==bottom)
		{
    
    
			arr[i][j]=cnt;
			break;
		}

		for(j=top;j<bottom;j++)
		{
    
    
			arr[i][j]=cnt;
			cnt++;
		}
		for(i=top;i<bottom;i++)
		{
    
    
			arr[i][j]=cnt;
			cnt++;
		}
		for(j=bottom;j>top;j--)
		{
    
    
			arr[i][j]=cnt;
			cnt++;
		}
		for(i=bottom;i>top;i--)
		{
    
    
			arr[i][j]=cnt;
			cnt++;
		}
		top++;
		bottom--;
	}
for(i=0;i<num;i++)
{
    
    
	for(j=0;j<num;j++)
	{
    
    
		printf("%3d ",arr[i][j]);
	}
	printf("\n");
}
return 0;
}
     

パターンを印刷するアルゴリズムとほぼ同じです。下部と上部が印刷されるため、
上部と下部の2つの変数を設定します。アルゴリズムのコアはwhileステートメントループ全体にあります。

おすすめ

転載: blog.csdn.net/yooppa/article/details/114323723