问题描述:
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 ]
]
问题求解:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
//关键是要找到(x1,y1),(x2,y2)的位置,则上下左右的边界即可确定!!!
if(n <= 0) return {};
vector<vector<int>> matrix(n,vector<int>(n,0));//!!!
//(x1,y1)表示遍历每一圈左上角元素的位置(0,0),(1,1)...!!!
int x1=0, y1=0;
int index=1;
int cnt=n*n;
while(index <= cnt)
{//一共有cnt个位置需要赋值
//(x2,y2)表示遍历每一圈右下角元素的位置(n-1,n-1),(n-2,n-2)...!!!
int x2=n-1-x1;
int y2=n-1-y1;
for(int i=y1;i<=y2&&index<=cnt;i++)
{//从左到右
matrix[x1][i] = index;
index++;
}
for(int i=x1+1;i<x2&&index<=cnt;i++)
{//从上到下(不包括上界和下界)
matrix[i][y2] = index;
index++;
}
for(int i=y2;i>=y1&&index<=cnt;i--)
{//从右到左
matrix[x2][i] = index;
index++;
}
for(int i=x2-1;i>x1&&index<=cnt;i--)
{//从下到上(不包括上界和下界)
matrix[i][y1] = index;
index++;
}
x1++;y1++;
}
return matrix;
}
};
方法二:
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > matrix(n,vector<int>(n,0));
if(n <= 0) return matrix;
int cnt = n * n;
int index = 1;
int beginX = 0,endX = n - 1;
int beginY = 0,endY = n - 1;
while(index <= cnt){
//(1)从左到右
for(int i = beginY;i <= endY;++i){
matrix[beginX][i] = index;
++index;
}
++beginX;//从左到右结束后左上角元素横坐标加1
//(2)从上到下
for(int i = beginX;i <= endX;++i){
matrix[i][endY] = index;
++index;
}
--endY;//从上到下结束后右下角元素纵坐标减1
//(3)从右到左
for(int i = endY;i >= beginY;--i){
matrix[endX][i] = index;
++index;
}
--endX;//从右到左结束后右下角元素横坐标减1
//(4)从下到上
for(int i = endX;i >= beginX;--i){
matrix[i][beginY] = index;
++index;
}
++beginY;//从下到上结束后左上角元素纵坐标加1
}
return matrix;
}
};