方法1:找规律法
#include <iostream>
using namespace std;
int main(void)
{
int n;
while (cin >> n) {
if (n == 0) break;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << min(min(i + 1, j + 1), min(n - i, n - j)) << ' ';
}
cout << endl;
}
cout << endl;
}
return 0;
}
方法2:曼哈顿距离法
#include <iostream>
using namespace std;
int main(void)
{
int n;
while (cin >> n) {
if (n == 0) break;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (n % 2) // 奇数
cout << (n + 1) / 2 - max(abs(n / 2 - i), abs(n / 2 - j)) << ' ';
else
cout << (n + 1) / 2.0 - max(abs((n - 1) / 2.0 - i), abs((n - 1) / 2.0 - j)) << ' ';
}
cout << endl;
}
cout << endl;
}
return 0;
}
方法3:蛇形矩阵求解
#include <iostream>
#include <cstring>
using namespace std;
const int N = 100 + 10;
int m[N][N];
int main(void)
{
int n;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
while (cin >> n) {
memset(m, 0, sizeof(m));
if (n == 0) break;
int d = 0, x = 0, y = 0;
int cnt = 0;
int res = 1;
for (int i = 0; i < n * n; i++) {
int a = x + dx[d], b = y + dy[d];
m[x][y] = res;
if (a < 0 || a >= n || b < 0 || b >= n || m[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
cnt++;
if (!(cnt % 4)) res++;
}
x = a, y = b;
}
for (int i = 0; i < n; i ++){
for (int j = 0; j < n; j ++)
cout << m[i][j] << ' ';
cout << endl;
}
cout << endl;
}
return 0;
}