54. Spiral Matrix
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].
解法
设立四个指针,每次发生变化。
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0) {
return res;
}
if (matrix[0] == null || matrix[0].length == 0) {
return res;
}
int rowBegin = 0;
int rowEnd = matrix.length - 1;
int colBegin = 0;
int colEnd = matrix[0].length - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
// Traverse Right
for (int j = colBegin; j <= colEnd; j++) {
res.add(matrix[rowBegin][j]);
}
rowBegin++;
// Traverse Down
for (int i = rowBegin; i <= rowEnd; i++) {
res.add(matrix[i][colEnd]);
}
colEnd--;
// Traverse Left
if (rowBegin <= rowEnd) {
for (int j = colEnd; j >= colBegin; j--) {
res.add(matrix[rowEnd][j]);
}
rowEnd--;
}
// Traverse Up
if (colBegin <= colEnd) {
for (int i = rowEnd; i >= rowBegin; i--) {
res.add(matrix[i][colBegin]);
}
colBegin++;
}
}
return res;
}
}