54. Spiral Matrix
Last updated
Last updated
time: O(mn)
space: O(mn)
why
if (rowStart <= rowEnd) {
// ๅ ็บๅ้ขๆ rowStart++ ๅ colEnd--, ๅผๆๆนๅ, ๆไปฅ้ฟๅ
ๅจ while ๅ
ง้็่ถ
้
// ๆไปฅ่ฆๅคๅ ๅคๆท
if (colStart <= colEnd) {
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0) return res;
int rowStart = 0;
int rowEnd = matrix.length - 1;
int colStart = 0;
int colEnd = matrix[0].length - 1;
while (colStart <= colEnd && rowStart <= rowEnd) {
if (rowStart <= rowEnd) { //้ฝๅ
for (int i = colStart; i <= colEnd; i++) {
res.add(matrix[rowStart][i]);
}
}
rowStart++;
if (colStart <= colEnd) { //้ฝๅ
for (int i = rowStart; i <= rowEnd; i++) {
res.add(matrix[i][colEnd]);
}
}
colEnd--;
if (rowStart <= rowEnd) { //้ฝๅ
for (int i = colEnd; i >= colStart; i--) {
res.add(matrix[rowEnd][i]);
}
}
rowEnd--;
if (colStart <= colEnd) { //้ฝๅ
for (int i = rowEnd; i >= rowStart; i--) {
res.add(matrix[i][colStart]);
}
}
colStart++;
}
return res;
}
}