Description:
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]
.
Solution:
第一种想法是类似找迷宫出口,即先申请一个isvisited的bool数组用于标记已经走过的元素地址,重复思考一下发现没有必要浪费空间,因为题意要求的运动是很有规律的:从 左上角出发一直循环访问数组中每一个元素,所以只要能数学地表达出到达边界时做出的反应即可。这里使用了四个循环分别代表最上行从左到右、最右列从上到下、最下方从右到左、最左行从下到上。值得注意的是最左行从下到上时不能访问当前圈数的最左上角元素,否则就会陷入死循环,因此我们还需要一个标记circles记录当前圈数,这样就能自动不断缩小圈数循环。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.size() <= 0)
return result;
int steps = 0, i = 0, j = 0, circles = 0;
int m = matrix.size(), n = matrix[0].size();
result.push_back(matrix[0][0]);
steps++;
while (steps < m * n) {
while (steps < m * n && j < n - circles - 1) {
j++;
steps++;
result.push_back(matrix[i][j]);
//cout << "i: " << i << " j: " << j << " element: " << matrix[i][j] << " " << endl;
}
while (steps < m * n && i < m - circles - 1) {
i++;
steps++;
result.push_back(matrix[i][j]);
//cout << "i: " << i << " j: " << j << " element: " << matrix[i][j] << " " << endl;
}
while (steps < m * n && j > circles) {
j--;
steps++;
result.push_back(matrix[i][j]);
//cout << "i: " << i << " j: " << j << " element: " << matrix[i][j] << " " << endl;
}
while (steps < m * n && i > circles + 1) {
i--;
steps++;
result.push_back(matrix[i][j]);
//cout << "i: " << i << " j: " << j << " element: " << matrix[i][j] << " " << endl;
}
circles++;
}
return result;
}
};