Write a square spiral matrix with an array

Code example:

#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;
}
     

It is almost the same as the algorithm for printing patterns. The bottom and top are printed so set the
top and bottom two variables. The core of the algorithm is in the entire while statement loop.

Guess you like

Origin blog.csdn.net/yooppa/article/details/114323723