博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hdu1998 奇数阶魔法 (数组填数)
阅读量:2232 次
发布时间:2019-05-09

本文共 1793 字,大约阅读时间需要 5 分钟。

奇数阶魔方

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3071    Accepted Submission(s): 1614


Problem Description
一个 n 阶方阵的元素是1,2,...,n^2,它的每行。每列和2条对角线上元素的和相等。这样
的方阵叫魔方。n为奇数时我们有1种构造方法。叫做“右上方” 。比如以下给出n=3。5,7时
的魔方.
3
8 1 6
3 5 7
4 9 2
5
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
7
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
第1行中间的数总是1,最后1行中间的数是n^2,他的右边是2。从这三个魔方,你可看出“右
上方”是何意。 
 

Input
包括多组数据。首先输入T,表示有T组数据.每组数据1行给出n(3<=n<=19)是奇数。

 

Output
对于每组数据,输出n阶魔方,每一个数占4格,右对齐
 

Sample Input
 
2 3 5
 

Sample Output
 
8 1 6 3 5 7 4 9 2 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
 

Author
Zhousc@ECJTU
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:            

这道题怎么说呢,当我看到这样的题的第一眼就是肯定是找规律,并且整个数组都遵循。。

由于你要编程序吧。。肯定不会太复杂的规律。。

所以就花费了5分钟找到规律。

拿n=5为样例,a[0][n/2]=1,a[n-1][n/2]=n*n,a[n-1][n/2+1]=2.然后你会发现3在2的右上方

5在4的右上方6在5的正下方。。。

等等。。

我们就会发现假如m在a[x][y]位置。那么m+1就在a[x-1][i+1]位置(当然其他条件都满足的情况下),

至于其他条件不满足的情况,就是a[x-1][i+1]上面已经有数,那么m+1应该在m的以下。

还有假设m在a[x][n-1],那么m+1就在a[x-1][0].假设m

在a[0][y]那么m+1就在a[n-1][y+1]。

假设m在a[0][n-1],m+1也在m的以下。

附上代码吧:

#include 
#include
int main(){ int map[20][20],ncase,n; scanf("%d",&ncase); while(ncase--) { memset(map,0,sizeof(map)); scanf("%d",&n); map[n-1][n/2]=n*n; map[0][n/2]=1; int t=2; int i=n-1,j=n/2+1; while(t
=0&&i
=0) map[i][j]=t,i--,j++,t++; else { if(i<0&&j
=0&&j==n) j=0; else i+=2,j--; } } for(int i=0;i

转载于:https://www.cnblogs.com/ljbguanli/p/6857036.html

你可能感兴趣的文章
【LEETCODE】53-Maximum Subarray
查看>>
【LEETCODE】215-Kth Largest Element in an Array
查看>>
【LEETCODE】241-Different Ways to Add Parentheses
查看>>
【LEETCODE】312-Burst Balloons
查看>>
【LEETCODE】232-Implement Queue using Stacks
查看>>
【LEETCODE】225-Implement Stack using Queues
查看>>
【LEETCODE】155-Min Stack
查看>>
【LEETCODE】20-Valid Parentheses
查看>>
【LEETCODE】290-Word Pattern
查看>>
【LEETCODE】36-Valid Sudoku
查看>>
【LEETCODE】205-Isomorphic Strings
查看>>
【LEETCODE】204-Count Primes
查看>>
【LEETCODE】228-Summary Ranges
查看>>
【LEETCODE】27-Remove Element
查看>>
【LEETCODE】66-Plus One
查看>>
【LEETCODE】26-Remove Duplicates from Sorted Array
查看>>
【LEETCODE】118-Pascal's Triangle
查看>>
【LEETCODE】119-Pascal's Triangle II
查看>>
【LEETCODE】190-Reverse Bits
查看>>
【学习方法】如何分析源代码
查看>>