fork(43) download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. void print_spiral (int ** matrix, int size);
  5.  
  6. int main()
  7. {
  8. int ** matrix = new int * [4];
  9. for (int i=0; i<4; i++) matrix[i] = new int[4];
  10.  
  11. // { 7, 8, 9, 10 },
  12. // { 6, 1, 2, 11 },
  13. // { 5, 4, 3, 12 },
  14. // { 16, 15, 14, 13 }
  15.  
  16. matrix[0][0] = 7; matrix[0][1] = 8; matrix[0][2] = 9; matrix[0][3] = 10;
  17. matrix[1][0] = 6; matrix[1][1] = 1; matrix[1][2] = 2; matrix[1][3] = 11;
  18. matrix[2][0] = 5; matrix[2][1] = 4; matrix[2][2] = 3; matrix[2][3] = 12;
  19. matrix[3][0] = 16; matrix[3][1] = 15; matrix[3][2] = 14; matrix[3][3] = 13;
  20.  
  21. print_spiral(matrix, 4);
  22.  
  23. return 0;
  24. }
  25.  
  26. void print_spiral (int ** matrix, int size)
  27. {
  28. int x = 0; // current position; x
  29. int y = 0; // current position; y
  30. int d = 0; // current direction; 0=RIGHT, 1=DOWN, 2=LEFT, 3=UP
  31. int c = 0; // counter
  32. int s = 1; // chain size
  33.  
  34. // starting point
  35. x = ((int)floor(size/2.0))-1;
  36. y = ((int)floor(size/2.0))-1;
  37.  
  38. for (int k=1; k<=(size-1); k++)
  39. {
  40. for (int j=0; j<(k<(size-1)?2:3); j++)
  41. {
  42. for (int i=0; i<s; i++)
  43. {
  44. std::cout << matrix[x][y] << " ";
  45. c++;
  46.  
  47. switch (d)
  48. {
  49. case 0: y = y + 1; break;
  50. case 1: x = x + 1; break;
  51. case 2: y = y - 1; break;
  52. case 3: x = x - 1; break;
  53. }
  54. }
  55. d = (d+1)%4;
  56. }
  57. s = s + 1;
  58. }
  59. }
  60.  
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15