n=3
1 2 3
8 9 4
7 6 5
n=4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
1 2 3
8 9 4
7 6 5
n=4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include "misc.h" class SpiralArray{ public: vector<vector<int>> getMatrix(int n){ if(n==0) return vector<vector<int>>(); vector<vector<int>> ret(n, vector<int>(n, 0)); int L = n/2; int t = 0; for(int l=0; l<L; ++l){ //top int i = l; for(int j=l; j<n-1-l; ++j) ret[i][j] = ++t; //right int j = n-1-l; for(int i=l; i<n-1-l; ++i) ret[i][j] = ++t; //bottom i = n-1-l; for(int j=n-1-l; j>l; --j) ret[i][j] = ++t; //left j = l; for(int i=n-1-l; i>l; --i) ret[i][j] = ++t; } if(n%2==1) ret[n/2][n/2] = ++t; return ret; } }; int main(){ SpiralArray sa; vector<vector<int>> ret = sa.getMatrix(4); for(auto r:ret){ for(auto c:r) cout<<c<<" "; cout<<endl; } return 0; } |
No comments:
Post a Comment