测试所有代码:
#include#include #include #include #include #include #include #include using namespace std;const int M = 5;const int N = 6;vector
> build_spiral_matrix(int m, int n);vector print_spiral_matrix(const vector > &vec);int main() { auto mat1=build_spiral_matrix(M, N); for (int j = 0;j < M;++j) { copy(mat1[j].begin(), mat1[j].end(), ostream_iterator (cout, " ")); cout << endl; } auto ans2 = print_spiral_matrix(mat1); copy(ans2.begin(), ans2.end(), ostream_iterator (cout, " ")); return 0;}//螺旋矩阵的构造vector > build_spiral_matrix(int m, int n) { vector > ans(m, vector (n, 0)); int index = 0; int i; int bx = 0; int ex = n - 1; int by = 0; int ey = m - 1; while (1) { for (i = bx;i <= ex;++i) { ans[by][i] = ++index; } if (++by>ey) break; for (i = by;i <= ey;++i) { ans[i][ex] = ++index; } if (--ex = bx;--i) { ans[ey][i] = ++index; } if (--ey = by;--i) { ans[i][bx] = ++index; } if (++bx>ex) break; } return ans;}//螺旋矩阵的打印vector print_spiral_matrix(const vector > &vec) { vector ans; if (vec.size() == 0) { return ans; } int bx = 0; int ex = vec[0].size() - 1; int by = 0; int ey = vec.size() - 1; int i; while (1) { for (i = bx;i <= ex;++i) { ans.push_back(vec[by][i]); } if (++by>ey) break; for (i = by;i <= ey;++i) { ans.push_back(vec[i][ex]); } if (--ex = bx;--i) { ans.push_back(vec[ey][i]); } if (--ey = by;--i) { ans.push_back(vec[i][bx]); } if (++bx>ex) break; } return ans;}