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)
{
vector<vector<int> > matrix;
int temp = 0;
for(int i=0;i<n;i++)
{
vector<int> line;
for(int j=0;j<n;j++)
{
line.push_back(temp);
}
matrix.push_back(line);
}
vector<int> res;
int x = 0, y = 0, tot = 1; //tot用于计数,作为停止条件
int up = 0, down = n-1, left = 0, right = n-1;
if(n==0) //错误输入数据,特殊处理
return matrix;
//开始遍历
while(tot <= n*n)
{
while(x==up && tot <= n*n) //最上面一行
{
matrix[x][y] = tot;
tot++;
if(y == right)
x++;
else
y++;
}
up += 1;
while(y==right && tot <= n*n)
{
matrix[x][y] = tot;
tot++;
if(x == down)
y--;
else
x++;
}
right -= 1;
while(x==down && tot <= n*n)
{
matrix[x][y] = tot;
tot++;
if(y == left)
x--;
else
y--;
}
down -= 1;
while(y==left && tot <= n*n)
{
matrix[x][y] = tot;
tot++;
if(x == up)
y++;
else
x--;
}
left += 1;
}
//cout<<up<<down<<left<<right;
return matrix;
}
};
附上solution区代码:
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > ret( n, vector<int>(n) );
int k = 1, i = 0;
while( k <= n * n )
{
int j = i;
// four steps
while( j < n - i ) // 1. horizonal, left to right
ret[i][j++] = k++;
j = i + 1;
while( j < n - i ) // 2. vertical, top to bottom
ret[j++][n-i-1] = k++;
j = n - i - 2;
while( j > i ) // 3. horizonal, right to left
ret[n-i-1][j--] = k++;
j = n - i - 1;
while( j > i ) // 4. vertical, bottom to top
ret[j--][i] = k++;
i++; // next loop
}
return ret;
}
};