fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. const int MAX_SIZE = 50;
  5.  
  6. int main() {
  7. int mtSize, windLine[MAX_SIZE + 1][MAX_SIZE + 1];
  8. cin >> mtSize;
  9. for (int line = 1; line <= mtSize; ++line) {
  10. for (int col = 1; col <= mtSize; ++col) {
  11. cin >> windLine[line][col];
  12. }
  13. }
  14. int lineDir = 0, colDir = 1;
  15. /*
  16. pop.ga.flaviu
  17. 2024-02-11 10:36:11
  18. Initialize 'lineDir' with the value of -1 and think how it could help you make your code shorter
  19. */
  20. for (int linePos = 1, colPos = 1; linePos <= mtSize && colPos <= mtSize;) {
  21. /*
  22. pop.ga.flaviu
  23. 2024-02-11 10:35:24
  24. Instead of 'mtSize * mtSize' use 2 variables, i and j, and multiple conditions.
  25.  
  26. Also, declare the 'linePos' and 'colPos' in the for loop's condition
  27. */
  28. cout << windLine[linePos][colPos] << " ";
  29. int lPlusC = linePos + colPos;
  30. if (lPlusC % 2 && ((lineDir == 0 && colDir == 1 && lPlusC <= mtSize + 1)
  31. /*
  32. pop.ga.flaviu
  33. 2024-02-11 10:37:16
  34. Let's use only 1 if statement here to print the result, then 1 if-else if.
  35. */
  36. || (lineDir == 1 && colDir == 0 && lPlusC >= mtSize + 1))) {
  37. lineDir = 1;
  38. colDir = -1;
  39. }
  40. if (lPlusC % 2 == 0 && ((lineDir == 0 && colDir == 1
  41. && lPlusC >= mtSize + 1) || (lineDir == 1 && colDir == 0
  42. && lPlusC <= mtSize + 1))) {
  43. lineDir = -1;
  44. colDir = 1;
  45. }
  46. if ((lineDir == 1 && colDir == -1 && lPlusC < mtSize + 1 && colPos == 1)
  47. || (lineDir == -1 && colDir == 1 && lPlusC >= mtSize + 1
  48. && colPos == mtSize)) {
  49. lineDir = 1;
  50. colDir = 0;
  51. }
  52. if ((lineDir == 1 && colDir == -1 && lPlusC >= mtSize + 1
  53. && linePos == mtSize) || (lineDir == -1 && colDir == 1 &&
  54. lPlusC < mtSize + 1 && linePos == 1 )) {
  55. lineDir = 0;
  56. colDir = 1;
  57. }
  58. linePos += lineDir;
  59. colPos += colDir;
  60. lPlusC = linePos + colPos;
  61. }
  62. return 0;
  63. }
Success #stdin #stdout 0.01s 5288KB
stdin
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
stdout
1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16