1. 程式人生 > >【模板小程序】循環方陣構造(仿《劍指offer》循環矩陣打印)

【模板小程序】循環方陣構造(仿《劍指offer》循環矩陣打印)

tar r++ () main end sin pri name str

 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 }

【模板小程序】循環方陣構造(仿《劍指offer》循環矩陣打印)