#include <iostream> using namespace std; int main() { int arr[4][4]={1,2,4,7,3,5,8,11,6,9,12,14,10,13,15,16}; int n=4; for (int k = 0; k <= 2 * (n - 1); ++k) { int yMin = max(0, k - n + 1); int yMax = min(n - 1, k); for (int y = yMin; y <= yMax; ++y) { int x = k - y; std::cout<<" "<<arr[y][x]<<" "; } } }
行列不等 向左下斜
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
char arr[5][3]={'a','b','d','c','e','g','f','h','j','i','k','m','l','n','o'};
int row_size =5;
int col_size =3;
for (int line = 1; line <= (col_size + row_size - 1); line++)
{
int start_row = max(0, line - col_size);
int count = std::min({ line, (row_size - start_row), col_size });
// cout<<" "<<count;
for (int j = 0; j < count; j++) {
int col_idx = start_row + j;
int row_idx = min(col_size, line) - j - 1;
cout<<" "<<arr[col_idx][row_idx]<<" ";
}
}
}
https://stackoverflow.com/questions/21346343/traverse-an-array-diagonally
https://www.geeksforgeeks.org/zigzag-or-diagonal-traversal-of-matrix/
https://www.baeldung.com/java-loop-diagonal-array