小陈的开学第十一周程序

一、Wlacm

1.曲径通幽

题意

在N×N的方格中填入正整数1~N^2,可以有很多种方案。 如果按照迂回的路线(如下图)填数,你能给出比较有效的解法吗?
在这里插入图片描述

输入

正整数N(≤30)

输出

1~N^2构成的N×N数值方阵,输出时每个数值占4个位置。

样例输入

1
2
3
4

样例输出

   1

   1   4
   2   3

   1   4   5
   2   3   6
   9   8   7

   1   4   5  16
   2   3   6  15
   9   8   7  14
  10  11  12  13

解题思路

其实我本来是不会写这道题的,后来别的题写不出来就开始写这道题。刚开始我真的毫无思绪,后来就开始找规律,发现了它走位的小规律,就开始模拟,居然过了,但是应该写的不是很规范。

程序代码:(my_AC)

#include<bits/stdc++.h>
using namespace std;
int res[1000][1000];
int main(){
   
	int n;
	while(~scanf("%d",&n)){
   
		int cnt=4,x=1,y=3;
		res[1][1]=1;
		res[2][1]=2;
		res[2][2]=3;
		res[1][2]=4;
		int num=1;
		if(n<=2){
   
			for(int i=1;i<=n;i++){
   
				for(int j=1;j<=n;j++){
   
					printf("%4d",res[i][j]);
				}
				printf("\n");
			}
			continue;
		}
		for(int i=1;i<=(n+1)/2;i++){
   
	//		cout<<1<<endl;
			res[x][y]=++cnt;x++;
			int temp=x+num;
			while(x<=temp)
				res[x++][y]=++cnt;y--;x--;
			temp=y-num;
			num++;
			while(y>=temp)
				res[x][y--]=++cnt;y++;x++;
			temp=y+num+1;
			while(y<=temp)
				res[x][y++]=++cnt;y--;x--;
			temp=x-num;
			while(x>=temp)
				res[x--][y]=++cnt;y++;x++;
			num++;
		}
		for(int i=1;i<=n;i++){
   
			for(int j=1;j<=n;j++){
   
				printf("%4d",res[i][j]);
			}
			printf("\n");
		}
	}
	return 0;
} 

程序代码

#include"bits/stdc++.h"
using namespace std;
int map1[1000][1000];
int main(){
   
	int n;
	cin>>n;
	map1[1][1]=1;
	map1[2][1]=2;
	int num=3,x=2,y=1;
	for(int i=1;i<n;i++){
   
		int temp=i;
		if(i%2==1){
   
			temp=i;
			while(temp--){
   map1[x][++y]=num++;}
			temp=i;
			while(temp--){
   map1[--x][y]=num++;}
			map1[x][++y]=num++;
		}else {
   
			temp=i;
			while(temp--){
   map1[++x][y]=num++;}
			temp=i;
			while(temp--){
   map1[x][--y]=num++;}
			map1[++x][y]=num++;
		}
	}
	for(int i=1;i<=n;i++){
   
		for(int j=1;j<=n;j++){
   
			printf("%4d",map1[i][j]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值