做幻方
Time Limit:1000MS Memory Limit:1024K
Description:
Apple最近迷上了做幻方,Apple还是个中高手,只要你说个奇数N,他就能把N*N的幻方做出来。其实你可以比他做得更好的。Apple总是画得很乱,而你可以利用程序排得很整齐^_^ 幻方的要求:每一行,每一列,还有两条斜线上数字的和都相等。Input:
每行有一个数N(0< N < 30),输入0结束。Output:
输入一个奇数,输出一个幻方,每个数占3格,顺序参照样板输出,输出完以后加一个回车。Sample Input:
5 1 0
Sample Output:
11 18 25 2 9 10 12 19 21 3 4 6 13 20 22 23 5 7 14 16 17 24 1 8 15 1
Hint:
如果不会做幻方的请从1开始数到最后,相信你会发现其中的规律。当然输出也要按照这样的格式。Source:
Zhang Anpingcode :
1 /* 2 本题中需要注意幻方只能是题中所给出的格式,输出与其对称的格式将会WA。 3 代码中被注释掉的部分和未被注释掉的部分,功能其实是相同的,两个代码输出的幻方格式成上下对称。 4 */ 5 #include <iostream> 6 #include<iomanip> 7 using namespace std; 8 9 int main() 10 { 11 /* 12 int m = 0; 13 for (int n;cin >> n;) { 14 if (n == 0) break; 15 int magicSquare[30][30] = {0}; 16 magicSquare[0][n / 2] = 1; 17 int pre_row = 0, 18 pre_col = n / 2; 19 for (int i = 2; i <= n * n; i++) { 20 int row = pre_row - 1, 21 col = pre_col + 1; 22 row = (row < 0 ? n + row : row) % n; 23 col = col % n; 24 if (magicSquare[row][col] != 0) { 25 row = pre_row + 1; 26 col = pre_col; 27 } 28 pre_row = row; 29 pre_col = col; 30 magicSquare[row][col] = i; 31 } 32 for (int i = 0; i < n; i++) { 33 for (int j = 0; j < n; j++) { 34 cout << setw(3) << magicSquare[i][j]; 35 } 36 cout << endl; 37 } 38 if (m++ == 0) cout << endl; 39 } 40 */ 41 int m = 0; 42 for (int n;cin >> n;) { 43 if (n == 0) break; 44 int magicSquare[30][30] = {0}; 45 magicSquare[n - 1][n / 2] = 1; 46 int pre_row = n - 1, 47 pre_col = n / 2; 48 for (int i = 2; i <= n * n; i++) { 49 int row = pre_row + 1, 50 col = pre_col + 1; 51 row = (row < 0 ? n + row : row) % n; 52 col = (col < 0 ? n + col : col) % n; 53 if (magicSquare[row][col] != 0) { 54 row = pre_row - 1; 55 col = pre_col; 56 } 57 pre_row = row; 58 pre_col = col; 59 magicSquare[row][col] = i; 60 } 61 for (int i = 0; i < n; i++) { 62 for (int j = 0; j < n; j++) { 63 cout << setw(3) << magicSquare[i][j]; 64 } 65 cout << endl; 66 } 67 cout << endl; 68 } 69 }