A spiral walk

Topic links: A spiral walk

Time limit: C / C ++ 1 second, 2 seconds languages other
space restrictions: C / C ++ 32768K, other languages 65536k
64bit the IO the Format: LLD%

题目描述
Oh how the cows love to walk in their square pasture with sides of length N (1 <= N <= 750) and which is partitioned into N*N squares. They enjoy the sights, the smells, and the general ambience of the grass and trees.
Bessie has decided to take the cows on the longest possible walk from the upper left corner to the center (or near the center when N is even) of the pasture, passing through each and every square along the way after starting.
She has decided to create the obvious clockwise spiral route (example below) for this evening’s stroll. Write a program to create a map for her that shows the order of squares she should visit.
By way of example, for pastures of size N=3 and N=4, here are the
routes Bessie should use:
1 2 3   1 2 3 4
. 4. 9 14. 8 12 is 13 is. 5
. 7. 6 15. 6 16. 5. 11
    10. 9. 8. 7
Input Description:

  • Line 1: A single integer: N
    output Description:
  • Lines 1…N: N space-separated integers
    输入
3

Export

1 2 3
8 9 4
7 6 5

Subject to the effect

Topic should be well understood, not explained

Problem-solving ideas

The output as four steps, namely sideways, vertically, sideways down, vertically down, then look at the code it! It is quite well understood!

Code

#include<bits/stdc++.h>
using namespace std;
int mmp[1000][1000];
int main()
{
	int n;
	cin>>n;
	int m=n*n;
	int k=1,x=1,y=n;
	int f=1;
	while(x<y)
	{
		for(int j=x;j<y;j++)//横着从第x行第x列开始到y-x列 
			mmp[x][j]=k++;
		for(int j=x;j<y;j++)//竖着从第y列第x行到第y-x行 
			mmp[j][y]=k++;
		for(int j=0;j<y-x;j++)//从横着第y行第y列开始到x+1列 
			mmp[y][y-j]=k++;
		for(int j=0;j<y-x;j++)//从横着第x列第y行到第y-x列 
			mmp[y-j][x]=k++;	
		x++,y--;//每次循环让x++,y--;缩小正方形的大小 
	}
	if(n&1) mmp[n/2+1][n/2+1]=m;//如果是奇数,中间数需要自己设计; 
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		cout<<mmp[i][j]<<" ";
		cout<<"\n";
	}
	return 0;
}
Published 49 original articles · won praise 14 · views 4347

Guess you like

Origin blog.csdn.net/qq_43750980/article/details/103749782