PTA serpentine matrix (spiral square matrix)

PTA serpentine matrix (spiral square matrix)

Spiral square matrix (20 points) The
so-called "spiral square matrix" means that for any given N, the numbers from 1 to N×N start from the first grid in the upper left corner and fill in N× in the clockwise spiral direction. N's phalanx. This question requires the construction of such a square spiral matrix.

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

Output format:
output N×N spiral square matrix. There are N numbers in each line, and each number occupies 3 digits.

Input example:
5
Output example:
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

Ideas

Very simple, let’s assume n=3; to get such a serpentine matrix

  1  2  3
  8  9  4
  7  6  5

Fill in sequentially starting from 1. Suppose the coordinates of the "pen" are (x, y), then at the beginning x=0, y=n-1, that is, row 0, column 0 (the range of rows and columns is 0~n-1, there is no column n) . The movement track of the "pen" is: right, right, right, down, down, left, left, up, and right. In short, first right, until it can not be filled, then down, then left, and finally up. "Cannot fill in" means to go out of bounds again (for example, 5→6), or to go to the previously filled grid (for example, 8→9).

If all the grids are initialized to 0, it can be easily judged. At this time, memset() is used; the header file of this function is <string.h>.

#include<stdio.h>
#include<string.h>
#define maxn 20
int a[maxn][maxn];
int main()
{
    
    
int n, x, y, tot = 0;
scanf("%d", &n);
memset(a, 0, sizeof(a));
tot = a[x=0][y=0] = 1;
while(tot < n*n)
{
    
    
while(y+1<n && !a[x][y+1]) a[x][++y] = ++tot;
while(x+1<n && !a[x+1][y]) a[++x][y] = ++tot;
while(y-1>=0 && !a[x][y-1]) a[x][--y] = ++tot;
while(x-1>=0 && !a[x-1][y]) a[--x][y] = ++tot;

}
for(x = 0; x < n; x++)
{
    
    
for(y = 0; y < n; y++) printf("%3d", a[x][y]);
printf("\n");
}
return 0;
}

If you enter 6 you will get such a spiral matrix;

Guess you like

Origin blog.csdn.net/Potestatem/article/details/115014187