fork download
  1. #include <stdio.h>
  2. #define N 102
  3. void pp(int a[][N], int n)
  4. {
  5. for (int i = 1; i <= n; ++i)
  6. {
  7. for (int j = 1; j <= n ; ++j)
  8. {
  9. if (a[i][j])
  10. printf("%5d" , a[i][j]);
  11. else printf("%5s", "");
  12. }
  13. putchar('\n');
  14. }
  15. }
  16. int main()
  17. {
  18. int n, sideLength;
  19. int a[N][N];
  20. printf("n(1~9999) = ");
  21. scanf("%d", &n);
  22. for (sideLength = 0; sideLength * sideLength < n; ++sideLength);
  23. // initialize
  24. for (int i = 0; i <= sideLength + 1; ++i)
  25. for (int j = 0; j <= sideLength + 1; ++j)
  26. {
  27. a[i][j] = 0;
  28. if (i == 0 || j == 0 || i == sideLength + 1 || j == sideLength + 1 )
  29. a[i][j] = -1;
  30. }
  31. int x = 1, y = 1, dx = 1, dy = 0;
  32. for (int i = 1; i <= n; ++i)
  33. {
  34. a[y][x] = i;
  35. if (a[y + dy][x + dx])
  36. {
  37. // change direction
  38. int t = -dy;
  39. dy = dx;
  40. dx = t;
  41. }
  42. x += dx;
  43. y += dy;
  44. }
  45. pp(a, sideLength);
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 2252KB
stdin
123
stdout
n(1~9999) =     1    2    3    4    5    6    7    8    9   10   11   12
   44   45   46   47   48   49   50   51   52   53   54   13
   43   80   81   82   83   84   85   86   87   88   55   14
   42   79  108  109  110  111  112  113  114   89   56   15
   41   78  107                           115   90   57   16
   40   77  106                           116   91   58   17
   39   76  105                           117   92   59   18
   38   75  104                           118   93   60   19
   37   74  103       123  122  121  120  119   94   61   20
   36   73  102  101  100   99   98   97   96   95   62   21
   35   72   71   70   69   68   67   66   65   64   63   22
   34   33   32   31   30   29   28   27   26   25   24   23