[Discover interesting topics] [Array] Write spiral square array in C language

When learning programming in freshman year, the steps are loops, arrays, functions, and pointers.

Questions about spiral square matrices require at least knowledge of loops, tessellation, and arrays.

In the first year of learning C language, I used the knowledge I had learned for three months to write a solution to a spiral square matrix. When I was writing, I checked the online version. I found that nothing is the same, so I will share my method.

Line generation is also learning matrices recently. In this question, i represents the row and c represents the column.

For example, a 5*5 square matrix

1   2   3   4   5

16 17 18 19 6

15 24 25 20 7

14 23 22 21 8

13 12 11 10 9

Starting from a[0][0], in the first circle, the rows remain unchanged and the columns are increased incrementally. If added to five columns. (i and c start from zero, the code shows 4) and stop.

The columns are unchanged and the rows are incremented. Also increase to five. The rows are unchanged and the columns are decremented. The columns are unchanged and the rows are decremented.

That is to say, there will be four movements in each circle: right, lower, left and upper.

The same goes for the second lap. But you will find some changes in the numbers. This has something to do with the number of circles. Just find the relationship and list it.

The following is the source code I wrote


#include<stdio.h>
int main()
{
	int a[10][10];
	int i,c,n,m,k;

  scanf("%d",&n);            //如果n=5 
  i=0;c=0;
  m=1;
  for(k=1;k<=n/2+1;k++){
  	for(;c<=n-k;c++){        //c<=4,c<=3
  	  a[i][c]=m;
  	  m++;
		}
		  c=c-1;
		  m-=1;
  	  if(m==n*n+1){
			  break; }
  	for(;i<=n-k;i++){        //i<=4,i<=3
  		a[i][c]=m;
			m++; 
		}  
		  m-=1;
		  i=i-1;
		  if(m==n*n+1){
			  break; }
		for(i==c;c>=k-1;c--){    //c>=0,c>=1.
			a[i][c]=m;
			m++;
		}
		  m-=1;
		  c=c+1;
		  if(m==n*n+1){
			  break; }
		for(;i>=k;i--){        //i>=1,i>=2
			a[i][c]=m;
			m++;
		}
		  m-=1;
		  i=i+1;
		  if(m==n*n+1){
			  break; }
	}
	
	
	for(i=0;i<n;i++){
		for(c=0;c<n;c++){
			printf("%2d ",a[i][c]);
		}
		printf("\n");
	}
	
	return 0;
}
  	

After each direction is completed, it will be covered next time you turn the corner, so m-1. I think this method is very clumsy, and the code is also very large and long, and it is not concise at all. If anyone occasionally sees my articles. I hope you can take the trouble to help me correct it. This helps me a lot. Thanks for watching.
      

Guess you like

Origin blog.csdn.net/gelly_/article/details/120897128