题目描述:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
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].
这题和#381一样,只要设好了boundary,再注意下while loop break的条件,再仔细些就不会有问题。
Mycode(AC = 27ms):
class Solution {
public:
/**
* @param matrix a matrix of m x n elements
* @return an integer array
*/
vector<int> spiralOrder(vector<vector<int>>& matrix) {
// Write your code here
vector<int> ans;
int num_rows = matrix.size();
if (num_rows == 0) return ans;
ans.resize(num_rows * matrix[0].size());
int upper_row = 0,
down_row = num_rows - 1,
left_col = 0,
right_col = matrix[0].size() - 1,
count = 0;
while (count < ans.size()) {
// get upper row
for (int i = left_col; i <= right_col; i++) {
ans[count++] = matrix[upper_row][i];
}
upper_row++;
if (count >= ans.size()) break;
// get right col
for (int i = upper_row; i <= down_row; i++) {
ans[count++] = matrix[i][right_col];
}
right_col--;
if (count >= ans.size()) break;
// get bottom row
for (int i = right_col; i >= left_col; i--) {
ans[count++] = matrix[down_row][i];
}
down_row--;
if (count >= ans.size()) break;
// get left col
for (int i = down_row; i >= upper_row; i--) {
ans[count++] = matrix[i][left_col];
}
left_col++;
}
return ans;
}
};
本文介绍了一种将矩阵元素按螺旋顺序遍历的方法,并提供了一个通过边界控制实现螺旋遍历的具体算法实例。该算法适用于m x n大小的矩阵。
395

被折叠的 条评论
为什么被折叠?



