Analog: Spiral square

The so-called "square spiral" refers to any given N, the N × N to 1 starting from the upper left corner of the first digital lattice, clockwise helical direction sequentially filled in the N × N square matrix. This problem requires the construction of such square spiral.

Input format:
input line in a given positive integer N (<10).

Output format:
output of N × N square spiral. Each row of the N numbers, each of three bits.

Sample input:

5

Sample output:

  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

Problem solution 1:

#include <stdio.h>
int a[12][12];
int main()
{
    int n;
    scanf("%d", &n);
    int i=0,j=0,t=1, k;
    int m = n;
    while(t<=n*n){
        for(k=j; k<m; k++){
            a[i][k] = t++;
        }
        i++;
        for(k=i; k<m; k++){
            a[k][m-1] = t++;
        }
        m--;
        for(k=m-1; k>=j; k--){
            a[m][k] = t++;
        }
        for(k=m-1; k>=i; k--){
            a[k][j] = t++;
        }
        j++;
    }
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            printf("%3d", a[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Problem solution 2:

#include <stdio.h>
int main()
{
	int a[10][10];
	int n;
	int x=0,y=0;//坐标
	int k=1;//递增数字
	scanf("%d",&n);
	int wall0=n-1,wall1=n-1,wall2=0,wall3=1;//拐弯处的 
	int direction=0;//数字走向 0为右,1为下,2为左,3为上 
	while(k<=n*n)
	{
		if(direction==0)
		{
			a[x][y++]=k++;
			if(y==wall0)
			{
				direction=1;
				wall0--;
			}
		}//实现右到下 
		if(direction==1)
		{
			a[x++][y]=k++;
			if(x==wall1)
			{
				direction=2;
				wall1--; 
			}
		}//实现下到左 
		if(direction==2)
		{
			a[x][y--]=k++;
			if(y==wall2)
			{
				direction=3;
				wall2++;
			}
		}//实现左到上 
		if(direction==3)
		{
			a[x--][y]=k++;
			if(x==wall3)
			{
				direction=0;
				wall3++;
			}
		}//实现上到右 
	 } 
	 for(int i=0;i<n;i++)
	 {
	 	for(int j=0;j<n;j++)
	 	{
	 		printf("%3d",a[i][j]);
		 }
		 printf("\n");
	 }//循环输出 
	
	return 0;
}
Released three original articles · won praise 0 · Views 48

Guess you like

Origin blog.csdn.net/qq_18399061/article/details/104749369