A spiral walk

题目链接:A spiral walk

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO 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
8 9 4  12 13 14 5
7 6 5   11 16 15 6
    10 9 8 7
输入描述:

  • Line 1: A single integer: N
    输出描述:
  • Lines 1…N: N space-separated integers
    输入
3

输出

1 2 3
8 9 4
7 6 5

题目大意

题目应该很好理解,就不解释了

解题思路

将输出看成四个步骤,分别是横着,竖着,横着倒,竖着倒,然后看下代码吧!还是比较好理解的!

代码

#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;
}
发布了49 篇原创文章 · 获赞 14 · 访问量 4347

猜你喜欢

转载自blog.csdn.net/qq_43750980/article/details/103749782
今日推荐