Problem:
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]
.
Analysis:
Solutions:
C++:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> result;
if(matrix.empty() || matrix[0].empty())
return result;
int row_bound = matrix.size();
int col_bound = matrix[0].size();
int search_bound = min(matrix.size(), matrix[0].size()) / 2;
for(int i = 0; i < search_bound; ++i) {
for(int j = i; j < col_bound - i - 1; ++j)
result.push_back(matrix[i][j]);
for(int j = i; j < row_bound - i - 1; ++j)
result.push_back(matrix[j][col_bound - i - 1]);
for(int j = col_bound - i - 1; j > i; --j)
result.push_back(matrix[row_bound - i - 1][j]);
for(int j = row_bound - i - 1; j > i; --j)
result.push_back(matrix[j][i]);
}
if(min(matrix.size(), matrix[0].size()) % 2 != 0) {
for(int i = search_bound; i < max(row_bound, col_bound) - search_bound; ++i) {
if(row_bound > col_bound) {
result.push_back(matrix[i][search_bound]);
} else if(row_bound <= col_bound) {
result.push_back(matrix[search_bound][i]);
}
}
}
return result;
}
Java
:
Python: