题解 | #蛇形矩阵#
蛇形矩阵
https://www.nowcoder.com/practice/f228a074c5274619b26be544962375e1
#include <iostream> using namespace std; int main() { int A[1000][1000]; int n; cin >> n; int x = 0; int y = 0; int T = 1; int val = 1; for (int i=0;i<=n-1;i++) { if (T == 1) { for (x = i; x >= 0; x--) { A[x][i - x] = val; val++; } T = 0; } else { for (y = i; y >= 0; y--) { A[i - y][y] = val; val++; } T = 1; } } int h = 0; int m = 0; for (int i = n; i<=2*(n-1); i++) { if (T == 1) { for (x = n-1; x > h; x--) { A[x][i - x] = val; val++; } T = 0; } else { for (y = n-1; y > m; y--) { A[i - y][y] = val; val++; } T = 1; } h++; m++; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << A[i][j] << " "; } cout << endl; } system("pause"); return 0; } // 64 位输出请用 printf("%lld")