一、螺旋矩阵简介
螺旋矩阵是指一个呈螺旋状的矩阵,螺旋矩阵有如下的两种形式:
形式1:
n=2时
1 2
4 3
n=3时
1 2 3
8 9 4
7 6 5
形式2:
n=2时
1 2
4 3
n=3时
7 8 9
6 1 2
5 4 3
二、解题思路和代码实现
先向右移动,再向下,再向左,最后向上移动,重复这个过程直到走完全部的位置,思路很简单,看代码:
形式1的代码:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
int cnt=0;
int b = 0, e = n - 1;
int i = 0,j=0;
vector<vector<int>> data(n,vector<int>(n));
while (1)
{
//右上
while (j <= e)
{
data[i][j++] = ++cnt;
}
j--;
i++;
while (i <= e)
{
data[i++][j] = ++cnt;
}
i--;
j--;
//左下
while (j >= b)
{
data[i][j--] = ++cnt;
}
j++;
i--;
while (i >= b+1)
{
data[i--][j] = ++cnt;
}
if (cnt == n*n)
break;
i++;
j++;
b++;
e--;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << data[i][j] << " ";
}
cout << endl;
}
}
return 0;
}
形式2的代码:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
vector<vector<int>> data(n,vector<int>(n));
int x, y;
//确定1的位置(x,y)
if (n % 2 == 0)
{
x = n / 2 - 1;
y = n / 2 - 1;
}
else
{
x = n / 2 ;
y = n / 2;
}
int cnt = 0;
int step = 1;
int temp = y;
while (1)
{
while (y<=temp+step && cnt < n*n)
{
data[x][y++] = ++cnt;
}
y--;
temp = x;
x++;
while (x <= temp + step && cnt < n*n)
{
data[x++][y] = ++cnt;
}
x--;
temp = y;
y--;
step++;
while (y >= temp - step && cnt < n*n)
{
data[x][y--] = ++cnt;
}
y++;
temp = x;
x--;
while (x >= temp - step && cnt < n*n)
{
data[x--][y] = ++cnt;
}
x++;
temp = y;
y++;
step++;
if (cnt == n*n)
break;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << data[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}