54. Spiral Matrix(中等)

时间:2024-10-12 08:34:26

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].

下面的代码是这样办的: 1 2 3, 6 9, 8 7, 4, 5.

题意为旋转输出矩阵元素.

人家想法: travel路线: right -> down -> left -> up 循环直到违反循环条件(rb <= re && cb <= ce)为止.

重点是控制 row_begin, row_end, col_begin and col_end. 注意循环条件,以及 left 和 up 时的条件判断.

下面代码展现的思想特清楚.

人个想法,自个代码:

\(O(n^2)\) time, \(O(1)\) extra space.

vector<int> spiralOrder(vector<vector<int>>& A) {
vector<int> res;
if (A.size() == 0) return res; const int m = A.size(), n = A[0].size();
int rb = 0, re = m - 1, cb = 0, ce = n - 1; while (rb <= re && cb <= ce) {
// right travel
for (int j = cb; j <= ce; j++)
res.push_back(A[rb][j]);
rb++; // down travel
for (int j = rb; j <= re; j++)
res.push_back(A[j][ce]);
ce--; // left travel
if (rb <= re) {
for (int j = ce; j >= cb; j--)
res.push_back(A[re][j]);
}
re--; // up travel
if (cb <= ce) {
for (int j = re; j >= rb; j--)
res.push_back(A[j][cb]);
}
cb++;
}
return res;
}