题目描述
有一个 n 行不定列的矩阵,请你从矩阵左上角位置,按照倒倒 N 形走位,依次填入 1 ~ x 数字。比如对于一个 3 行不定列矩阵,依次填入 1 ~ 8 数字的结果如下:
1 6 7
2 5 8
3 4
输入描述
输入一行,两个正整数 n 和 x,其中 n 不大于 1000。
输出描述
输出结果矩阵,格式见用例
用例
输入
3 16
Copy
输出
1 6 7 12 13
2 5 8 11 14
3 4 9 10 15 16
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int M = 1e6 + 10;
void solve() {int n, x;cin >> n >> x;int m = (x + n - 1) / n; // 列数,x 需要分布在 n 行中vector<vector<int>> matrix(n, vector<int>(m, 0));int current = 1; // 从数字 1 开始填充for (int col = 0; col < m; col++) {if (col % 2 == 0) {// 从上到下填充for (int row = 0; row < n && current <= x; row++) {matrix[row][col] = current++;}} else {// 从下到上填充for (int row = n - 1; row >= 0 && current <= x; row--) {matrix[row][col] = current++;}}}for (int i = 0; i < n; i++) {bool first = true;for (int j = 0; j < m; j++) {if (matrix[i][j] != 0) {if (!first) cout << " ";cout << matrix[i][j];first = false;}}cout << endl;}}signed main() {solve();return 0;
}