https://leetcode.com/problems/spiral-matrix/
Given a matrix ofmxnelements (mrows,ncolumns), 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].
模拟题
思路也是简单明了:
但是对于层 我们需要确定遍历的范围,用两点就足够:top-left and bottom-right (same for rectangle)
当我们没遍历完一遍 我们可以相应的更新这两点
int si = 0;
int sj = 0;
int ei = m - 1;
int ej = n - 1;
while (si <= ei && sj <= ej) {
// up
for (int j = sj; j <= ej && si <= ei && sj <= ej; ++j) {
result.add(matrix[si][j]);
}
si++;
// right
for (int i = si; i <= ei && si <= ei && sj <= ej; ++i) {
result.add(matrix[i][ej]);
}
ej--;
// down
for (int j = ej; j >= sj && si <= ei && sj <= ej; --j) {
result.add(matrix[ei][j]);
}
ei--;
// left
for (int i = ei; i >= si && si <= ei && sj <= ej; --i) {
result.add(matrix[i][sj]);
}
sj++;
}
但其实 我们不需要那么多check, 1st for just from while, so no need to check again, 2nd we just update si, but we checked in our for, also no need. for 3rd j >= sj also means ej >= sj.
// following already contains all checking above
while (si <= ei && sj <= ej) {
// up
for (int j = sj; j <= ej; ++j) {
result.add(matrix[si][j]);
}
si++;
// right
for (int i = si; i <= ei; ++i) {
result.add(matrix[i][ej]);
}
ej--;
// down
for (int j = ej; j >= sj && si <= ei; --j) {
result.add(matrix[ei][j]);
}
ei--;
// left
for (int i = ei; i >= si && sj <= ej; --i) {
result.add(matrix[i][sj]);
}
sj++;
}