/*
方法:螺旋矩阵其实都可以从起始点(或者叫做最小点开始)赋值开始,然后观察每次向右移,向下,向左,向上,向右分别进行了n次赋值,之后的循环都是要n - 2
3
7 8 9
6 1 2
5 4 3
5
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
经过观察,大概有以下的规律:
n为阶数,a[n][n]为该矩阵
a[floor(n/2)][floor(n/2)]为首位,要循环的次数为n/2,圈数circle为2
1.向右移动1格(赋值)
2.向下移circle - 1格(分别赋值)
3.向左移circle - 1格(分别赋值)
4.向上移circle - 1格(分别赋值)
5.向左移circle - 1格(分别赋值)
circle += 2;
以1为(0,0)点,建立平面坐标系,求f(x,y)
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
while(1)
{
int n;
cout << "Please input odd number" << endl;
while(cin >> n && n % 2 == 0)
{
cout << "Please input odd number" << endl;
}
int a[n][n];
int circle = 2 , row = n / 2 , col = n / 2 , range = n / 2;
a[row][col] = 1;
int i = 1;
while(range)
{
i = i + 1;
col = col + 1;
a[row][col] = i;
for(int j = 0;j < circle - 1;j ++)
{
i = i + 1;
row = row + 1;
a[row][col] = i;
}
for(int j = 0;j < circle;j ++)
{
i = i + 1;
col = col - 1;
a[row][col] = i;
}
for(int j = 0;j < circle;j ++)
{
i = i + 1;
row = row - 1;
a[row][col] = i;
}
for(int j = 0;j < circle;j ++)
{
i = i + 1;
col = col + 1;
a[row][col] = i;
}
circle = circle + 2;
range = range - 1;
}
for(int j = 0;j < n;j ++)
{
for(int k = 0;k < n;k ++)
{
cout << left << setw(5) << a[j][k] ;
}
cout << endl;
}
}
return 0;
}
方法:螺旋矩阵其实都可以从起始点(或者叫做最小点开始)赋值开始,然后观察每次向右移,向下,向左,向上,向右分别进行了n次赋值,之后的循环都是要n - 2
3
7 8 9
6 1 2
5 4 3
5
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
经过观察,大概有以下的规律:
n为阶数,a[n][n]为该矩阵
a[floor(n/2)][floor(n/2)]为首位,要循环的次数为n/2,圈数circle为2
1.向右移动1格(赋值)
2.向下移circle - 1格(分别赋值)
3.向左移circle - 1格(分别赋值)
4.向上移circle - 1格(分别赋值)
5.向左移circle - 1格(分别赋值)
circle += 2;
以1为(0,0)点,建立平面坐标系,求f(x,y)
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
while(1)
{
int n;
cout << "Please input odd number" << endl;
while(cin >> n && n % 2 == 0)
{
cout << "Please input odd number" << endl;
}
int a[n][n];
int circle = 2 , row = n / 2 , col = n / 2 , range = n / 2;
a[row][col] = 1;
int i = 1;
while(range)
{
i = i + 1;
col = col + 1;
a[row][col] = i;
for(int j = 0;j < circle - 1;j ++)
{
i = i + 1;
row = row + 1;
a[row][col] = i;
}
for(int j = 0;j < circle;j ++)
{
i = i + 1;
col = col - 1;
a[row][col] = i;
}
for(int j = 0;j < circle;j ++)
{
i = i + 1;
row = row - 1;
a[row][col] = i;
}
for(int j = 0;j < circle;j ++)
{
i = i + 1;
col = col + 1;
a[row][col] = i;
}
circle = circle + 2;
range = range - 1;
}
for(int j = 0;j < n;j ++)
{
for(int k = 0;k < n;k ++)
{
cout << left << setw(5) << a[j][k] ;
}
cout << endl;
}
}
return 0;
}