```
def spiralOrder(self, matrix: 'List[List[int]]') -> 'List[int]':
if not matrix:
return[]
res = []
r1, r2 = 0, len(matrix) - 1
c1, c2 = 0, len(matrix[0]) - 1
while r1 <= r2 and c1 <= c2:
for i in range(c1, c2 + 1):
res.append(matrix[r1][i])
for i in range(r1 + 1, r2 + 1):
res.append(matrix[i][c2])
if r1 < r2 and c1 < c2:
for i in range(c2 - 1, c1 , -1):
res.append(matrix[r2][i])
for i in range(r2, r1, -1):
res.append(matrix[i][c1])
r1 += 1; r2 -= 1
c1 += 1; c2 -= 1
return res
```

c1, c2, r1, r2 defines a matrix. Each iteration of the while loop will peel off the outmost layer of the matrix.

# Corner cases

## 1 dim matrix

[[1,2,3,4]

The if statement in while is used to deal with the fact in such case. since r1 = r2, we don’t need to collect entry vertically. We also have collected horizontally in the first for loop, so we can jump through the second horizontal for loop.

The same with vertical 1 dim matrix.