Skip to content

Commit 3dae8da

Browse files
committed
Time: 0 ms (100%), Space: 43.2 MB (9.46%) - LeetHub
1 parent 18b192e commit 3dae8da

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
class Solution {
3+
public List<Integer> spiralOrder(int[][] matrix) {
4+
List<Integer> result = new ArrayList<>();
5+
int n = matrix.length, m = matrix[0].length;
6+
int left = 0, right = m - 1, top = 0, bottom = n - 1;
7+
8+
9+
while (left <= right && top <= bottom) {
10+
// left to right
11+
for(int j = left; j <= right; j++) {
12+
result.add(matrix[top][j]);
13+
}
14+
top++;
15+
// top to bottom
16+
for(int i = top; i <= bottom; i++) {
17+
result.add(matrix[i][right]);
18+
}
19+
20+
right--;
21+
if (left > right || top > bottom) {
22+
break;
23+
}
24+
// right to left
25+
for(int j = right; j >= left; j--) {
26+
result.add(matrix[bottom][j]);
27+
}
28+
bottom--;
29+
// bottom to top
30+
for(int i = bottom; i >= top; i--) {
31+
result.add(matrix[i][left]);
32+
}
33+
left++;
34+
}
35+
36+
return result;
37+
}
38+
}

0 commit comments

Comments
 (0)