洛谷 P2615 神奇的幻方

洛谷 P2615 神奇的幻方

传送门

I'm here!


思路

这个题,我们可以直接去模拟,因为范围很小,且(N)都是奇数
直接构造一个矩阵,初始值都为(0),然后(while)循环,根据题目给出的(4)个条件进行模拟,将矩阵一个个赋值为(1)~(nast n)中的元素,这样就完成了
时间空间:(28ms,912KB)


代码

#include<bits/stdc++.h>
#define N 40
using namespace std;

int a[N][N]={0};
int n;
int x,y,tot=1;

int main(){
	cin>>n;
	int b=n/2+1;
	a[x=1][y=b]=tot;
	while(tot<=n*n){
		//按照题目给出的条件直接模拟
		if(x==1&&y!=n)a[x=n][++y]=++tot;
		if(x!=1&&y==n)a[--x][y=1]=++tot;
		if(x==1&&y==n)a[++x][y]=++tot;
		if(x!=1&&y!=n){
			if(a[x-1][y+1]==0){
				a[--x][++y]=++tot;
			}
			else{
				a[++x][y]=++tot;
			}
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cout<<a[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/loceaner/p/10894433.html