1 /* 2 本程序说明: 3 4 输入:方阵大小n,输出:n*n的旋转方阵 5 6 举例: 7 当n=2时,输出: 8 1 2 9 4 3 10 当n=4时,输出: 11 1 2 3 4 12 12 13 14 5 13 11 16 15 6 14 10 9 8 7 15 16 */ 17 #include <iostream> 18 #include <vector> 19 20 using namespace std; 21 22 void PrintMatrixInCircle(vector<int>& numbers, int columns, int rows, int start,int& number) 23 { 24 int endX = columns - 1 - start; 25 int endY = rows - 1 - start; 26 27 // 从左到右打印一行 28 for(int i = start; i <= endX; ++i) 29 { 30 numbers[start*columns+i]=number++; 31 } 32 33 // 从上到下打印一列 34 if(start < endY) 35 { 36 for(int i = start + 1; i <= endY; ++i) 37 { 38 numbers[i*columns+endX]=number++; 39 } 40 } 41 42 // 从右到左打印一行 43 if(start < endX && start < endY) 44 { 45 for(int i = endX - 1; i >= start; --i) 46 { 47 numbers[endY*columns+i]=number++; 48 } 49 } 50 51 // 从下到上打印一行 52 if(start < endX && start < endY - 1) 53 { 54 for(int i = endY - 1; i >= start + 1; --i) 55 { 56 numbers[i*columns+start]=number++; 57 } 58 } 59 } 60 61 void PrintMatrixClockwisely(vector<int>& numbers, int columns, int rows,int& number) 62 { 63 int start = 0; 64 65 while(columns > start * 2 && rows > start * 2) 66 { 67 PrintMatrixInCircle(numbers, columns, rows, start, number); 68 ++start; 69 } 70 } 71 72 73 int main() 74 { 75 int n; 76 while(cin>>n) 77 { 78 int number=1; 79 vector<int> numbers(n*n,0); 80 PrintMatrixClockwisely(numbers, n, n, number); 81 for(int i=0;i<n*n;++i) 82 { 83 if(0==i%n &&i!=0) 84 cout<<endl; 85 cout<<numbers[i]<<" "; 86 } 87 cout<<endl; 88 } 89 return 0; 90 }
时间: 2024-10-13 12:03:40