fork(6) download
  1. #include <stdio.h>
  2. #define N_ROWS 5
  3. #define N_COLS 3
  4.  
  5. void print_spiral(int a[N_ROWS][N_COLS])
  6. {
  7. enum {up, down, left, right} direction = right;
  8. int up_limit = 0,
  9. down_limit = N_ROWS - 1,
  10. left_limit = 0,
  11. right_limit = N_COLS - 1,
  12. downcount = N_ROWS * N_COLS,
  13. row = 0,
  14. col = 0;
  15.  
  16. while(printf("%d ", a[row][col]) && --downcount)
  17. if(direction == right)
  18. {
  19. if(++col > right_limit)
  20. {
  21. --col;
  22. direction = down;
  23. ++up_limit;
  24. ++row;
  25. }
  26. }
  27. else if(direction == down)
  28. {
  29. if(++row > down_limit)
  30. {
  31. --row;
  32. direction = left;
  33. --right_limit;
  34. --col;
  35. }
  36. }
  37. else if(direction == left)
  38. {
  39. if(--col < left_limit)
  40. {
  41. ++col;
  42. direction = up;
  43. --down_limit;
  44. --row;
  45. }
  46. }
  47. else /* direction == up */
  48. if(--row < up_limit)
  49. {
  50. ++row;
  51. direction = right;
  52. ++left_limit;
  53. ++col;
  54. }
  55. }
  56.  
  57. int main()
  58. {
  59. int a[N_ROWS][N_COLS] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
  60. print_spiral(a);
  61. return 0;
  62. }
Success #stdin #stdout 0.02s 1720KB
stdin
Standard input is empty
stdout
1 2 3 6 9 12 15 14 13 10 7 4 5 8 11