题解 | #蛇形矩阵#
蛇形矩阵
https://www.nowcoder.com/practice/f228a074c5274619b26be544962375e1
#include <iostream> using namespace std; int main() { int n; cin >> n; int a[n][n]; int i = 1; int row = 0; int col = 0; int layer = 1; while (1) { if (layer % 2 == 0) { a[row][col] = i; row++; col--; i++; if (layer < n && col == -1) { col = 0; layer++; } if ((layer == n && col == -1) || (layer > n && row == n)) { col = col + 2; row--; layer++; } } if (layer % 2 == 1) { a[row][col] = i; row--; col++; i++; if (layer < n && row == -1) { row = 0; layer++; } if ((layer == n && row == -1) || (layer > n && col == n)) { row = row + 2; col--; layer++; } } if (i == n * n + 1) break; } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout << a[i][j] << " "; } cout << endl; } } // 64 位输出请用 printf("%lld")
我的思路是按对角线分层,第一层是1,第二层是2,3,第三层是4,5,6……中间一层刚好是n(矩阵的维度),然后就按题目意思操作就行,分为在层数小于n,层数等于n和层数大于n数组越界的处理。
C++题解 文章被收录于专栏
记录在牛客网用C++刷题的题解思路