fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <array>
  5.  
  6. struct Point
  7. {
  8. size_t x;
  9. size_t y;
  10. Point() : x(0), y(0) {}
  11. Point(size_t x, size_t y) : x(x), y(y) {}
  12.  
  13. Point operator+(const Point& p) const
  14. {
  15. return Point(x + p.x, y + p.y);
  16. }
  17.  
  18. bool operator==(const Point& p) const
  19. {
  20. return x == p.x && y == p.y;
  21. }
  22. };
  23.  
  24. const std::array<Point, 4> clockwise {
  25. Point(+1, 0), //right
  26. Point(0, +1), //down
  27. Point(-1, 0), //left
  28. Point(0, -1), //up
  29. };
  30.  
  31. const std::array<Point, 4> counterClockwise {
  32. Point(0, +1), //down
  33. Point(+1, 0), //right
  34. Point(0, -1), //up
  35. Point(-1, 0), //left
  36. };
  37.  
  38. struct Grid
  39. {
  40. std::vector<std::vector<int>> grid;
  41. size_t size;
  42.  
  43. Grid(size_t size)
  44. {
  45. this->size = size;
  46. for(size_t i = 0; i < size; i++)
  47. {
  48. grid.push_back(std::vector<int>(size));
  49. std::fill(grid[i].begin(), grid[i].end(), 0);
  50. }
  51. }
  52.  
  53. bool withinBounds(const Point& p)
  54. {
  55. return 0 <= p.x && p.x < size && 0 <= p.y && p.y < size;
  56. }
  57.  
  58. void fill(bool reverse)
  59. {
  60. Point current(0, 0);
  61. size_t directionIndex = 0;
  62. auto direction = reverse ? counterClockwise : clockwise;
  63. for(int number = 1, end = size * size; number <= end; number++)
  64. {
  65. grid[current.y][current.x] = number;
  66. auto next = current + direction[directionIndex];
  67. if(!withinBounds(next) || grid[next.y][next.x] != 0)
  68. {
  69. directionIndex = (directionIndex + 1) % 4;
  70. next = current + direction[directionIndex];
  71. }
  72. current = next;
  73. }
  74. }
  75.  
  76. friend std::ostream& operator<<(std::ostream& out, const Grid& g);
  77. };
  78.  
  79. std::ostream& operator<<(std::ostream& out, const Grid& g)
  80. {
  81. for(size_t y = 0; y < g.size; y++)
  82. {
  83. for(size_t x = 0; x < g.size; x++)
  84. {
  85. out << g.grid[y][x] << '\t';
  86. }
  87. out << std::endl;
  88. }
  89. return out;
  90. }
  91.  
  92. int main()
  93. {
  94. int n;
  95. std::string direction;
  96. std::cin >> n;
  97. std::cin >> direction;
  98.  
  99. Grid grid(n);
  100. grid.fill(direction == "reverse");
  101. std::cout << grid << std::endl;
  102. }
Success #stdin #stdout 0s 16064KB
stdin
4
reverse
stdout
1	12	11	10	
2	13	16	9	
3	14	15	8	
4	5	6	7