**Solution**

**Spiral Matrix** https://leetcode.com/problems/spiral-matrix/

- The idea is simple. Maintain four variables rs,re,cs,ce. Use these four to peel off the outer layer of the matrix described by those four parameters. Then update those four parameters until you hit boundary conditions.
- The devil lies in the following:

- Be very careful with for loops printing rows and columns. Pay special attention to rs,re,cs,ce.
- Be very careful with edge cases like [], [[1,2,3]], [[1],[2],[3]] i.e empty matrix, single row matrix, and single column matrix.

```
class Solution(object):
def outer_layer(self, matrix, rs, re, cs, ce, result):
for j in range(cs, ce+1):
result.append(matrix[rs][j])
if rs == re:
return
for i in range(rs+1, re+1):
result.append(matrix[i][ce])
if cs == ce:
return
for j in range(ce-1, cs-1, -1):
result.append(matrix[re][j])
for i in range(re-1, rs, -1):
result.append(matrix[i][cs])
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if matrix == []:
return []
M, N = len(matrix), len(matrix[0])
rs, re, cs, ce = 0, M-1, 0, N-1
result = []
while rs <= re and cs <= ce:
self.outer_layer(matrix, rs, re, cs, ce, result)
rs, re = rs+1, re-1
cs, ce = cs+1,ce-1
return result
```

Another interesting problem: https://www.youtube.com/watch?v=IDxaZrrggu0