2045: [Example 5.13] Serpentine filling

topic

2045: [Example 5.13] Serpentine filling

Time Limit: 1000 ms Memory Limit: 65536 KB
Number of Submissions: 1201 Number of Passes: 626
[Title Description]
Fill in 1,2,3,…,n×n in an n×n square matrix, and it is required to fill in a snake shape. For example, when n=4, the square matrix is:

10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
Among them, n≤20.

【Input】
Enter n.

【Output】
Output the square matrix of the title. n lines, each number is separated by a space.

【Input example】
4
【Output example】
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4


Topic analysis: It is difficult to directly find the data corresponding to a certain coordinate, but we can divide the square matrix into multiple layers, fill in the outermost layer first, then fill in the second layer...until the square matrix is ​​filled. If the side length of the original square matrix is ​​n, then it becomes a square matrix with side length (n-2) after filling the outermost layer. Through the side length of the square matrix, we can find the outermost data.


C++ code

#include<iostream>
using namespace std;
int main()
{
    
    
	int a[20][20],n;
	cin>>n;
	int c=n,temp=1;//c:当前矩阵边长;temp:当前数字
	while(c)
	{
    
    
		if(c==1)//只有一个格
		{
    
    
			a[n/2][n/2]=temp;
			break;
		}
		int y=(n-c)/2,x=(n-c)/2+c-1;
		int end=y+c-1;
		for(;y<=end;y++,temp++)//处理右面
		{
    
    
			a[y][x]=temp;
		}
		y=end;
		end=x-c+1;
		x--;
		for(;x>=end;x--,temp++)//处理下面
		{
    
    
			a[y][x]=temp;
		}
		x=end;
		end=y-c+1;
		y--;
		for(;y>=end;y--,temp++)//处理左面
		{
    
    
			a[y][x]=temp;
		}
		y=end;
		end=x+c-1;
		x++;
		for(;x<end;x++,temp++)//处理上面
		{
    
    
			a[y][x]=temp;
		}
		c-=2;//矩阵边长缩小2
	}
	for(int i=0;i<n;i++)
	{
    
    
		for(int j=0;j<n;j++)
		{
    
    
			cout<<a[i][j]<<' ';
		}
		cout<<endl;
	}
}

operation result

5*5 serpentine square

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324212130&siteId=291194637