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]
.
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(matrix.size() == 0){
vector<int> spiralMatrix(0);
return spiralMatrix;
}
int halfCol = (matrix[0].size() - 1) / 2;
int halfRow = (matrix.size() - 1) / 2;
int col = 0;
int row = 0;
vector<int> spiralMatrix(0);
while(row <= halfRow && col <= halfCol){
for(int i = col; i < matrix[0].size() - col; i++){
spiralMatrix.push_back(matrix[row][i]);
}
for(int i = row + 1; i < matrix.size() - row; i++){
spiralMatrix.push_back(matrix[i][matrix[0].size() - col - 1]);
}
if(row != matrix.size() - row - 1){
for(int i = matrix[0].size() - col - 2; i >= col; i--){
spiralMatrix.push_back(matrix[matrix.size() - row - 1][i]);
}
}
if(col != matrix[0].size() - col){
for(int i = matrix.size() - row - 2; i >= row + 1; i--){
spiralMatrix.push_back(matrix[i][col]);
}
}
row++;
col++;
}
return spiralMatrix;
}