找出规律,并打印出一个NxN的矩阵,规律就是从首坐标开始顺时针依次增大:
#include<iostream>
#include<vector> using namespace std; int main(void)
{ int N;
cout << "Input a num:" << endl;
cin >> N;
while (N < )
{
cout << "invalid input!!!" << endl;
cout << "input again!!!" << endl;
cin >> N;
}
if (N == )
{
cout << ;
return ;
} vector<vector<int> > p(N);
for (int i = ; i < N; i++)
{
p[i].resize(N);//设置N*N的数组
}
int k = ;
for (int j = ; j < N / ;j++)
{
for (int i = j; i < N - j; i++)
{
p[j][i] = k;
k++;
}
for (int i = + j; i < N - j; i++)
{
p[i][N - j - ] = k;
k++;
}
for (int i = N - - j; i >= j; i--)
{
p[N - - j][i] = k;
k++;
}
for (int i = N - -j; i >j; i--)
{
p[i][j] = k;
k++;
}
}
if (N % == )
{
p[N / ][N / ] = k;
} for (int i = ; i < N; i++)
{
for (int j = ; j < N; j++)
{
cout << p[i][j] << "\t";
}
cout << endl;
}
return ;
}