fork download
  1. #include <iostream>
  2. #include <math.h> //log10(), floor()
  3.  
  4. int main()
  5. {
  6. int num, holder;
  7. int count = 1;
  8.  
  9. std::cin >> num;
  10. const int n = num > 0 ? num : -num;
  11. int spiral[n][n];
  12. int spaces = log10(n*n)+2; //stolen from /u/J354
  13.  
  14. for (int d = 0; d < n/2 + n%2; d++)
  15. { //Constructs the spiral one layer at a time
  16. for (int c = d; c < n-d-1; c++)
  17. { //Constructs the four sides of the layer
  18. spiral[d][c] = count;
  19. spiral[c][n-1-d] = (n-1-2*d) + count;
  20. spiral[n-1-d][n-1-c] = 2*(n-1-2*d) + count;
  21. spiral[n-1-c][d] = 3*(n-1-2*d) + count;
  22. count++;
  23. }
  24. count += 3*(n-1-2*d);
  25. }
  26. //Dirty fix for odd n
  27. if (n%2) {spiral[n/2][n/2] = n*n;}
  28.  
  29. if (num < 0)
  30. { //Flip if negative input
  31. for (int i = 0; i < n; i++)
  32. {
  33. for (int j = i; j < n; j++)
  34. {
  35. holder = spiral[i][j];
  36. spiral[i][j] = spiral[j][i];
  37. spiral[j][i] = holder;
  38. }
  39. }
  40. }
  41.  
  42. for (int i = 0; i < n; i++)
  43. { //Print output
  44. for (int j = 0; j < n; j++)
  45. {
  46. for (int s = spaces-floor(log10(spiral[i][j]))-1; s > 0; s--) {std::cout << " ";}
  47. std::cout << spiral[i][j];
  48. if (j == n-1) {std::cout << "\n";}
  49. }
  50. }
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 15240KB
stdin
4
5
-3
stdout
  1  2  3  4
 12 13 14  5
 11 16 15  6
 10  9  8  7