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;
if(matrix.size()==0) return res;
int n=matrix.size();
int m=matrix[0].size();
for (int row=0;row<n/2+1;row++)
{
int i=row;
int j=i;
for (j=i;j<(m-row);j++)
{
res.push_back(matrix[i][j]);
if (res.size()==(n*m))
{
return res;
}
}
j--;
for (i=row+1;i<(n-row);i++)
{
res.push_back(matrix[i][j]);
if (res.size()==(n*m))
{
return res;
}
}
i--;
for (j=j-1;j>=row;j--)
{
res.push_back(matrix[i][j]);
if (res.size()==(n*m))
{
return res;
}
}
j++;
for (i=i-1;i>=row+1;i--)
{
res.push_back(matrix[i][j]);
if (res.size()==(n*m))
{
return res;
}
}
}
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,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int x=0;
vector<vector<int>> res;
vector<int> temp(n,0);
for (int i=0;i<n;i++)
{
res.push_back(temp);
}
for (int row=0;row<n/2+1;row++)
{
int i=row;
int j=i;
for (j=i;j<(n-row);j++)//左---右
{
res[i][j]=++x;
}
j--;
for (i=row+1;i<(n-row);i++)//上---下
{
res[i][j]=++x;
}
i--;
for (j=j-1;j>=row;j--)//右---左
{
res[i][j]=++x;
}
j++;
for (i=i-1;i>=row+1;i--)//下---上
{
res[i][j]=++x;
}
}
return res;
}
};
Spiral Matrix && Spiral Matrix II
原文:http://blog.csdn.net/sinat_24520925/article/details/46442417