输入n=4
输出1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
程序变量解释:
#include <iostream> using namespace std; int main() { int n; cin >> n; int* arr = new int[n*n]; for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j) arr[i*n + j] = -1; } int tmp = n; int first = 1; int second = first + 1; int thrid = 4 * tmp - 4; int sum = second + thrid; int ntmp = n; for (int i = 0; tmp > 0 ; ++i){ arr[i*n + i] = first; for (int j = i+1; j < n-i; ++j){ arr[i * n + j] = first + j - i; arr[j * n + i] = sum - arr[i * n + j]; } for (int k = n-1-i; k >= n/2;--k){ for (int m = n - k; m <= k; ++m){ arr[m*n + k] = first + tmp + m - n + k ; arr[k*n + m] = sum - arr[m*n + k]; } } tmp -= 2; first = thrid + 1; second = first + 1; thrid += 4 * tmp - 4; sum = second + thrid; } for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j) cout << arr[i*n + j]<<" "; cout << endl; } return 0; }
结果如下:
本文出自 “零蛋蛋” 博客,谢绝转载!
原文:http://lingdandan.blog.51cto.com/10697032/1845614