问题描述
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路分析
这个题目的要求很明确:就是对二维数组进螺旋赋值行赋值操作:1,2,3,….n*2,赋值的方向为顺时针螺旋,由外而内。我们可以遍历该矩阵宽度的一半大小,找好赋值位置与i和j的数值关系顺序赋值即可。
代码展示
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> >matrix(n,vector<int>(n));
int i;
int count = n / 2;
int j;
int number = 1;
int mod = n % 2;
for (i = 0; i < count; i++)
{
for (int j = i; j < n - i - 1; j++)
{
matrix[i][j] = number++;
}
for (int j = i; j < n - 1 - i; j++)
{
matrix[j][n - 1 - i] = number++;
}
for (int j = n - i - 1; j >= i + 1; j--)
{
matrix[n - i - 1][j] = number++;
}
for (int j = n - 1 - i; j >= i + 1; j--)
{
matrix[j][i] = number++;
}
}
if (mod == 1)
matrix[count][count] = number;
return matrix;
}
};
int main(){
int n;
cout<<"请输入N:";
cin>>n;
Solution solution;
vector<vector<int> > result=solution.generateMatrix(n) ;
int size = result.size();
for(int i=0;i<size;i++){
int size1=result[i].size();
cout<<"[";
int j;
for(j=0;j<size1-1;j++){
cout<<result[i][j]<<", ";
}
cout<<result[i][j]<<"]"<<endl;
}
}
运行结果展示