#include #include struct M; struct Pos { struct _moves { int mx, my; } m[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; Pos(const M& m); bool next_valid(); bool next(); int x, y; int dir; const M &mref; }; struct M { M(int _l, int _c); void do_spiral(); void read(); int l, c, total; std::vector> v; Pos p; }; M::M(int _l, int _c): l(_l), c(_c), total(0), p(*this) { for (int i = 0; i < l; i++) v.push_back(std::vector(c)); } void M::do_spiral() { do { std::cout << v[p.x][p.y] << " "; v[p.x][p.y] = 0; } while (p.next()); std::cout << std::endl; } void M::read() { for (int i = 0; i < l; i++) for (int j = 0; j < c; j++) { int x; std::cin >> x; v[i][j] = x; } } Pos::Pos(const M& m) : x(0), y(0), dir(0), mref(m) {} bool Pos::next_valid() { int _x = x + m[dir].mx; int _y = y + m[dir].my; if ( _x < 0 || _x >= mref.l || _y < 0 || _y >= mref.c) return false; if (mref.v[_x][_y] == 0) return false; return true; } bool Pos::next() { int i = 0; while (!next_valid() && i < 4) { dir = (dir+1)%4; i++; } if (next_valid()) { x += m[dir].mx; y += m[dir].my; return true; } return false; } int main() { int l, c; std::cin >> l >> c; M m(l, c); m.read(); m.do_spiral(); return 0; }