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]
.
弄了一晚上就这么一个题。。。把自己弄晕了。。。两种方法,第一种用类似dp做一个bool table 来遍历。第二种就是 向右,向下,向左,向上。 其中向左和向上的时候检查是不是当前行列已经被打印,如果有,终止。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> res;
if (matrix.empty()||matrix[0].empty())
return res;
int x0, x1, y0, y1,i;
x0=0; y0=0;
x1=matrix.size()-1;y1=matrix[0].size()-1;
while(x0<=x1 && y0<=y1){
for (i=y0; i<=y1; i++)
res.push_back(matrix[x0][i]);
x0++;
for (i=x0;i<=x1; i++)
res.push_back(matrix[i][y1]);
y1--;
if (x0>x1) break;
for(i=y1;i>=y0; i--)
res.push_back(matrix[x1][i]);
x1--;
if(y0>y1) break;
for(i=x1;i>=x0; i--)
res.push_back(matrix[i][y0]);
y0++;
}
return res;
}
};