找出规律,并打印出一个NxN的矩阵,规律就是从首坐标开始顺时针依次增大:
1 #include<iostream> 2 #include<vector> 3 4 using namespace std; 5 6 int main(void) 7 { 8 9 int N; 10 cout << "Input a num:" << endl; 11 cin >> N; 12 while (N < 0) 13 { 14 cout << "invalid input!!!" << endl; 15 cout << "input again!!!" << endl; 16 cin >> N; 17 } 18 if (N == 0) 19 { 20 cout << 0; 21 return 0; 22 } 23 24 vector<vector<int> > p(N); 25 for (int i = 0; i < N; i++) 26 { 27 p[i].resize(N);//设置N*N的数组 28 } 29 int k = 0; 30 for (int j = 0; j < N / 2;j++) 31 { 32 for (int i = j; i < N - j; i++) 33 { 34 p[j][i] = k; 35 k++; 36 } 37 for (int i = 1 + j; i < N - j; i++) 38 { 39 p[i][N - j - 1] = k; 40 k++; 41 } 42 for (int i = N - 2 - j; i >= j; i--) 43 { 44 p[N - 1 - j][i] = k; 45 k++; 46 } 47 for (int i = N - 2-j; i >j; i--) 48 { 49 p[i][j] = k; 50 k++; 51 } 52 } 53 if (N % 2 == 1) 54 { 55 p[N / 2][N / 2] = k; 56 } 57 58 for (int i = 0; i < N; i++) 59 { 60 for (int j = 0; j < N; j++) 61 { 62 cout << p[i][j] << " "; 63 } 64 cout << endl; 65 } 66 return 0; 67 }