蛇形矩阵(从左下开始,斜填充)
作者:
M4LLKN0W
,
2024-05-22 18:59:11
,
所有人可见
,
阅读 7
#include <iostream>
using namespace std;
const int N = 1010;
int res[N][N];
int n, m;
int main() {
cin >> n >> m;
for (int d = 0, k = 1; d < n + m - 1; d ++ ) {
if (d % 2 == 0) { // up
int r = (d < m) ? n - 1 : m - 1 - (d - n + 1);
int c = (d < m) ? d : m - 1;
while (r >= 0 && c >= 0) {
res[r][c] = k ++ ;
r -- , c -- ;
}
} else { // down
int r = (d < n) ? n - 1 - d : 0;
int c = (d < n) ? 0 : d - n + 1;
while (r < n && c < m) {
res[r][c] = k ++ ;
r ++ , c ++ ;
}
}
}
for (int i = 0; i < n; i ++ ) {
for (int j = 0; j < m; j ++ )
cout << res[i][j] << " ";
cout << endl;
}
return 0;
}