螺旋输出N*N矩阵
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 int main() { 5 int x[] = { 0, 1, 0, -1 }; 6 int y[] = { 1, 0, -1, 0 }; 7 int n; 8 int pos_x = 0; 9 int pos_y = 0; 10 cin >> n; 11 int counter = 1; 12 vector<vector<int> > A(n, vector<int>(n, 0)); 13 int i; 14 for (i = n - 1; i > 0; i -= 2) { 15 for (int k = 0; k < 4; k++) { 16 for (int j = 0; j < i; j++) { 17 A[pos_x][pos_y] = counter; 18 counter++; 19 pos_x += x[k]; 20 pos_y += y[k]; 21 } 22 } 23 pos_x++; 24 pos_y++; 25 } 26 if (i == 0) 27 A[pos_x][pos_y] = counter; 28 for (int i = 0; i < n; i++) { 29 for (int j = 0; j < n; j++) { 30 cout << A[i][j] << " "; 31 } 32 cout << endl; 33 } 34 return 0; 35 }