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
dfs(vector
>& matrix, int dp){
vector
ret;
//每递归,顺时针一次 剔除 上下两行,左右两列,所以是-2dp
if ( (int)matrix.size()-2*dp <= 0 || (int)matrix[0].size()-2*dp <= 0 ){
return ret;
}
int colum = matrix[dp].size() - dp - 1;
int row = matrix.size() - dp - 1;
for (int i = dp; i <= colum; i++)//上行
ret.push_back(matrix[dp][i]);
for (int i = dp+1; i <= row; i++)// 右列
ret.push_back(matrix[i][colum]);
for (int i = colum - 1; row>dp && i >= dp; i--) // 下行row>上行dp ,不能和上面的行重了
ret.push_back(matrix[row][i]);
for (int i = row - 1; dp
dp; i--)//左列 dp< 右列colum ,不能和右列重了 ret.push_back(matrix[i][dp]); vector
tmpVec = dfs(matrix, dp + 1); ret.insert(ret.end(), tmpVec.begin(), tmpVec.end()); return ret; } vector
spiralOrder(vector
>& matrix) { return dfs(matrix, 0); } };