一、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]