标签:
Problem:
Write a program to: 1) wait for the user to input a positive integer N, and 2) output a NxN matrix on the screen with numbers 1 to N, rotating clockwise inward. For example, if N = 4, then the output should be:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Answer:
1 #include <iostream> 2 #include <vector> 3 4 using namespace std; 5 6 int main() 7 { 8 int N; 9 cin >> N; 10 int m = N; 11 int c = 0; 12 vector<vector<int> > a(N, vector<int>(N, 0)); 13 int i = 1; 14 int x = 0; 15 int y = 0; 16 int count = 0; 17 while (i <= N * N) { 18 a[x][y] = i; 19 ++i; 20 ++count; 21 if (x == c && y < m-1) { 22 ++y; 23 } 24 else if (y == m -1 && x < m-1) { 25 ++x; 26 } 27 else if (x == m - 1 && y > c) { 28 --y; 29 } 30 else if (y == c && x > c) { 31 --x; 32 } 33 if (count == (m-c)*4 - 4) { 34 ++c; 35 --m; 36 x = c; 37 y = c; 38 count = 0; 39 } 40 } 41 42 43 for (int j = 0; j < N; ++j) { 44 for (int k = 0; k < N; ++k) { 45 cout << a[j][k] << " "; 46 } 47 cout << endl; 48 } 49 50 return 0; 51 52 }
Rotating clockwise inward matrix
标签:
原文地址:http://www.cnblogs.com/unistation/p/4606129.html