1
class Solution {
2
public List<Integer> spiralOrder(int[][] matrix) {
3
List<Integer> ans = new ArrayList<>();
4
int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1;
5

6
while (top <= bottom && left <= right) {
7
for (int i = left; i <= right; i++) ans.add(matrix[top][i]);
8
top++;
9

10
for (int i = top; i <= bottom; i++) ans.add(matrix[i][right]);
11
right--;
12

13
if (top <= bottom) {
14
for (int i = right; i >= left; i--) ans.add(matrix[bottom][i]);
15
bottom--;
16
}
17

18
if (left <= right) {
19
for (int i = bottom; i >= top; i--) ans.add(matrix[i][left]);
20
left++;
21
}
22
}
23
return ans;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0