# Layer by Layer?

• ``````class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// absorb the elements layer by layer
// There is no particular algorithm involved
int rows = matrix.size(); // more generic
vector<int> res;
if(rows == 0) return res;
int cols = matrix[0].size();
spiralOrder(rows,cols,res,matrix);
return res;
}
private:
void spiralOrder(int rows, int cols, vector<int> &res, vector<vector<int>> matrix){
int x = 0;
int y = 0;
// ensure the rows and cols is valid
while(rows > 0 && cols > 0){
if(rows==1){
for(int i = 0; i < cols; i++) res.push_back(matrix[x][y++]);
break;
}else if(cols == 1){
for(int i = 0; i < rows; i++) res.push_back(matrix[x++][y]);
break;
}
// go right
for(int i = 0; i < cols-1; i++) res.push_back(matrix[x][y++]);
// go down
for(int i = 0; i < rows-1; i++) res.push_back(matrix[x++][y]);
// go left
for(int i = 0; i < cols-1; i++) res.push_back(matrix[x][y--]);
// go up
for(int i = 0; i < rows-1; i++) res.push_back(matrix[x--][y]);
rows -= 2;
cols -= 2;
// go to the diagonal element
x++;
y++;
}
return;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.