fork download
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define T ++k&=3
  7. #define R p=cx+u[k+1&3],q=cy+v[k+1&3]
  8. #define C 0<=p&&p<w&&0<=q&&q<h&&!a[q*w+p]
  9. #define D p=cx+u[k],q=cy+v[k]
  10. #define G cx=p,cy=q,a[q*w+p]=++i
  11.  
  12. int* buildSnailReverse(int* a, int w, int h)
  13. {
  14. memset(a,0,w*h*4);
  15. int xs=w>h?w-h:0,ys=h>w?h-w:0,p,q,i=1,k=w>=h?0:1,u[]={1,0,-1,0},v[]={0,1,0,-1},xi=1,yi=1;
  16. int cx=w/2,cy=(h-1)/2;
  17. if(w>h)
  18. cx=cy=(h-1)/2,xs++;
  19. if(w<h)
  20. cx=cy=w/2;
  21.  
  22. a[cy*w+cx]=i;
  23. while(yi++<=ys||xi++<=xs)
  24. D,G;
  25. while(i<h*w){
  26. R;
  27. if(C)
  28. T,G,D;
  29. else{
  30. D;
  31. if(C)
  32. G;
  33. else
  34. T,D;
  35. }
  36. }
  37. return a;
  38. }
  39.  
  40. void printArray(int *a, int w, int h)
  41. {
  42. for(int y = 0; y<h; y++){
  43. for(int x=0; x<w; x++){
  44. printf("%3d",a[y*w + x]);
  45. }
  46. printf("\n");
  47. }printf("\n");
  48. }
  49.  
  50. int main()
  51. {
  52. int w, h;
  53. //std::cin >> w >> h;
  54. w = 4, h = 10;
  55. int* a = new int[w * h];
  56. buildSnailReverse(a, w, h);
  57. printArray(a, w, h);
  58. delete[] a;
  59. return 0;
  60. }
  61.  
  62.  
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
 37 38 39 40
 36 15 16 17
 35 14  1 18
 34 13  2 19
 33 12  3 20
 32 11  4 21
 31 10  5 22
 30  9  6 23
 29  8  7 24
 28 27 26 25