fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. const int MAX_LENGTH = 50;
  5.  
  6. int main() {
  7. int noElem, mt[MAX_LENGTH][MAX_LENGTH];
  8. cin >> noElem;
  9.  
  10. // Citirea matricei
  11. for (int i = 0; i < noElem; ++i) {
  12. for (int j = 0; j < noElem; ++j) {
  13. cin >> mt[i][j];
  14. }
  15. }
  16.  
  17. // Traversarea meandrată a matricei
  18. for (int diag = 0; diag < 2 * noElem - 1; ++diag) {
  19. int start_row = diag < noElem ? diag : noElem - 1;
  20. int start_col = diag < noElem ? 0 : diag - noElem + 1;
  21.  
  22. if (diag % 2 == 0) {
  23. // Diagonale în sus (stânga la dreapta)
  24. for (int r = start_row, c = start_col; r >= 0 && c < noElem; --r, ++c) {
  25. cout << mt[r][c] << " ";
  26. }
  27. } else {
  28. // Diagonale în jos (dreapta la stânga)
  29. for (int r = start_col, c = start_row; r < noElem && c >= 0; ++r, --c) {
  30. cout << mt[r][c] << " ";
  31. }
  32. }
  33. }
  34.  
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0.01s 5292KB
stdin
3
1 2 3
4 5 6 
7 8 9
stdout
1 2 4 7 5 3 6 8 9