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> fun(vector<vector<int> > &matrix){ vector<int> result; int m = matrix.size(); int n = matrix[0].size(); int left = 0; int right = n-1; int top = 0; int bottom = m-1; while (left <= right && top <= bottom) { if (top <= bottom) { for (int i = left; i <= right; i++) { result.push_back(matrix[top][i]); } top++; } if (left <= right) { for (int i = top; i <= bottom; i++) { result.push_back(matrix[i][right]); } right--; } if (top <= bottom) { for (int i = right; i >= left; i--) { result.push_back(matrix[bottom][i]); } bottom--; } if (left <= right) { for (int i = bottom; i >= top; i--) { result.push_back(matrix[i][left]); } left++; } } return result;}
新闻热点
疑难解答