magic square
来源:互联网 发布:好听的中文歌 知乎 编辑:程序博客网 时间:2024/05/18 02:43
Magic Square
[Submit] [Go Back] [Status]
Description
If you have good observations skills, you may found that building a Magic Square is simple. A Magic Square has only an odd numberN of rows and columns. For this problem you could expect the values to be3N15. A Magic Square is created by integer numbers in the range from 1 to N2, with a peculiar property, the ``sum of the numbers" in each row, column and diagonal is the same value.
For example the case for n = 3 is:
M. Square Rows Columns Diagonals 8 1 6 8+1+6 = 15 8+3+4 = 15 8+5+2 = 15 3 5 7 3+5+7 = 15 1+5+9 = 15 4+5+6 = 15 4 9 2 4+9+2 = 15 6+7+2 = 15
Hint: Imagine that the square is rounded. That is, the last row is connected with the first row and the last column is connected with the first column. As shown in the examples, the starting point is the center of the first row and observe how the numbers are placed following diagonals. There is only one more thing to observe, what happens when you find a cell that is already in use.
Input
A file with several lines, each line has the value of n.
Output
For each input line, print N and the sum in the first line, followed by the magic square. To see a nice looking square, take into account the maximum length in characters ofN2 and print each number with the maximum length preceded by one space or blank character. Print one line between squares.
Sample Input
35
Sample Output
n=3, sum=15 8 1 6 3 5 7 4 9 2n=5, sum=65 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
数组从1开始
1的位置,当N为奇数时候,在正中间,N为偶数的时候,在中间左边,所以1的位置就是(N+1)/2;
2的位置,在1的下一列最后一行
3的位置,若右上角有数或到边缘了,则在2的上一行最左边的一列
4的位置,若右上角有数或到边缘,则在3的下一行同一列的位置,否则在斜边缘
同理。。。。
memset(board,0,sizeof(board)); h=1;l=(N+1)/2;//算1的位置 for(k=1;k<=N*N;k++){if(board[h][l]==0){board[h][l]=k;h=(h-1)%N; if(h==0) h=N;l=(l+1)%N; if(l==0) l=N;if(board[h][l]!=0) {h=(h+2)%N; if(h==0) h=N;l=(l-1)%N; if(l==0) l=N; }}else{board[(h=h+1)][l]=k;//若该数不再表格边缘,跳到下一行}
- magic square
- magic square
- Magic Square
- 1318. Magic Square
- ZOJ 2835 Magic Square
- xmu 1016 Magic Square
- Sicily 1302. Magic Square
- sicily 1318. Magic Square
- sicily 1302. Magic Square
- [数据结构]Magic-Square
- Chris and Magic Square
- Chris and Magic Square
- codeforces710c Magic Odd Square
- Forming a Magic Square
- USACO 3.2.5 magic square
- UVa 11221 - Magic square palindromes.
- codeforce710 C. Magic Odd Square
- CodeForces 710 Magic Odd Square
- 国行v880刷ICS4.0.3
- jQuery实现省市县三级联动菜单
- Win8新增快捷键
- ubuntu安装chrome报错解决
- 关闭虚拟机virtualbox
- magic square
- 朴素贝叶斯分类器本质上是线性分类器
- Linux 编程经典书籍推荐
- Spring-IOC配置(学习笔记)
- 为程序员量身定制的12个目标
- 3.3.2012
- HTML5实现圣诞树效果
- umbraco mvc角度看问题
- 70个面试技巧