【模板小程序】循环方阵构造(仿《剑指offer》循环矩阵打印)

时间:2022-03-07 04:47:29
 /*
本程序说明: 输入:方阵大小n,输出:n*n的旋转方阵 举例:
当n=2时,输出:
1 2
4 3
当n=4时,输出:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7 */
#include <iostream>
#include <vector> using namespace std; void PrintMatrixInCircle(vector<int>& numbers, int columns, int rows, int start,int& number)
{
int endX = columns - - start;
int endY = rows - - start; // 从左到右打印一行
for(int i = start; i <= endX; ++i)
{
numbers[start*columns+i]=number++;
} // 从上到下打印一列
if(start < endY)
{
for(int i = start + ; i <= endY; ++i)
{
numbers[i*columns+endX]=number++;
}
} // 从右到左打印一行
if(start < endX && start < endY)
{
for(int i = endX - ; i >= start; --i)
{
numbers[endY*columns+i]=number++;
}
} // 从下到上打印一行
if(start < endX && start < endY - )
{
for(int i = endY - ; i >= start + ; --i)
{
numbers[i*columns+start]=number++;
}
}
} void PrintMatrixClockwisely(vector<int>& numbers, int columns, int rows,int& number)
{
int start = ; while(columns > start * && rows > start * )
{
PrintMatrixInCircle(numbers, columns, rows, start, number);
++start;
}
} int main()
{
int n;
while(cin>>n)
{
int number=;
vector<int> numbers(n*n,);
PrintMatrixClockwisely(numbers, n, n, number);
for(int i=;i<n*n;++i)
{
if(==i%n &&i!=)
cout<<endl;
cout<<numbers[i]<<" ";
}
cout<<endl;
}
return ;
}