输入一个值为n的数,输出这样一个n*n的序列。如何简单实现?
for example 打印一个序列:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
[cpp]
#include <vector> #include <iostream> using namespace std; int main() { int n; int i, j; int t; int flag = 1; vector< vector<int> > Matrix; cout << "输入n: \n"; cin >> n; Matrix.resize(n); for(i=0; i<n; i++) Matrix[i].resize(n); i = j = 0; for(i=0; i<n; i++) for(j=0; j<n; j++) Matrix[i][j] = -1; i = j = 0; t = 1; while(t <= n*n) { if(flag == 1) { if(Matrix[i][j] == -1) { Matrix[i][j] = t; j++; if(j+1 >= n || Matrix[i][j+1] != -1) flag = 2; } } else if(flag == 2) { if(Matrix[i][j] == -1) { Matrix[i][j] = t; i++; if(i+1 >= n || Matrix[i+1][j] != -1) flag = 3; } } else if(flag == 3) { if(Matrix[i][j] == -1) { Matrix[i][j] = t; j--; if(j-1 < 0 || Matrix[i][j-1] != -1) flag = 4; } } else if(flag == 4) { if(Matrix[i][j] == -1) { Matrix[i][j] = t; i--; if(i-1 < 0 || Matrix[i-1][j] != -1) flag = 1; } } ++t; } for(i=0; i<n; i++) { for(j=0; j<n; j++) { cout << Matrix[i][j]; if(j!=n-1) cout << ' '; else cout << '\n'; } } return 0; }