Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]
.
这道题挺简单的,基本上算是一次性写出来的,就是设立一个对应的标志数组,然后按照螺旋的规则来遍历。
代码如下:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int height=matrix.size();
if( height==)
return res;
int width=matrix[].size();
vector<vector<int>> flag(height,vector<int>(width,));//用来记录是否走过
int m=;
int n=;
flag[][]=;
res.push_back(matrix[][]);
int step=;
while(step!= height* width)
{
while(n+<width&&flag[m][n+])
{
flag[m][n+]=;
res.push_back(matrix[m][n+]);
n+=;
step++;
}
while(m+<height&&flag[m+][n])
{
flag[m+][n]=;
res.push_back(matrix[m+][n]);
m+=;
step++;
}
while(n->=&&flag[m][n-])
{
flag[m][n-]=;
res.push_back(matrix[m][n-]);
n-=;
step++;
}
while(m->=&&flag[m-][n])
{
flag[m-][n]=;
res.push_back(matrix[m-][n]);
m-=;
step++;
}
}
return res;
}
};
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 ]
]
I写出来了的话,II就更简单了,在I上改一下就行了,代码如下:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> flag(n,vector<int>(n,));//用来记录是否走过
if(n==)
return flag;
int height=;
int width=;
int step=;
flag[][]=;
while(step!= n*n)
{
while(width+<n&&flag[height][width+]==)
{
width+=;
step++;
flag[height][width]=step;
}
while(height+<n&&flag[height+][width]==)
{
height+=;
step++;
flag[height][width]=step;
}
while(width->=&&flag[height][width-]==)
{
width-=;
step++;
flag[height][width]=step;
}
while(height->=&&flag[height-][width]==)
{
height-=;
step++;
flag[height][width]=step;
}
}
return flag; }
};