# Leetcode【54、59、885】

##### Python3 实现：
``````class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
m, n = len(matrix), len(matrix[0])
i = j = k = 0  # (i,j)表示坐标, k表示层数
ans = []
while True:
if i == k and j != n - 1 - k:  # 从左到右
ans.append(matrix[i][j])
j += 1
elif i != m - 1 - k and j == n - 1 - k:  # 从右到底
ans.append(matrix[i][j])
i += 1
elif i == m - 1 - k and j != k:  # 从底到左
ans.append(matrix[i][j])
j -= 1
elif i != k and j == k:  # 从左到上
ans.append(matrix[i][j])
i -= 1
if i == k:  # 遍历完一层，进入下一层
i += 1
j += 1
k += 1
else:  # 方阵情况(m=n)，最后输出最中心的数字
ans.append(matrix[i][j])
if len(ans) == m * n: # 达到长度，返回结果
return ans
``````

##### Python3 实现：
``````class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0] * n for _ in range(n)]
cnt = 1
i = j = k = 0  # (i,j)表示坐标, k表示层数
while cnt <= n * n:
if i == k and j != n - 1 - k:  # 从左到右
matrix[i][j] = cnt; cnt += 1
j += 1
elif i != n - 1 - k and j == n - 1 - k:  # 从右到底
matrix[i][j] = cnt; cnt += 1
i += 1
elif i == n - 1 - k and j != k:  # 从底到左
matrix[i][j] = cnt; cnt += 1
j -= 1
elif i != k and j == k:  # 从左到上
matrix[i][j] = cnt; cnt += 1
i -= 1
if i == k:  # 遍历完一层，进入下一层
i += 1; j += 1; k += 1
else:  # 最后填充最中心的数字
matrix[i][j] = cnt; cnt += 1
return matrix
``````

##### Python3 实现：
``````class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
ans = []
i, j = r0, c0  # (i,j)表示坐标位置
ans.append([i, j])
step = cnt = tour = 0  # step表示朝一个方向走step步, cnt表示转向次数, tour表示走完step步改变一次方向

while len(ans) < R * C:

if cnt % 2 == 0:  # 两次转向后对step值加1
step += 1
tmp = step

while tmp != 0 and tour % 4 == 0:  # 向东
tmp -= 1
j += 1
if 0 <= i < R and 0 <= j < C:  # 坐标不能越界
ans.append([i, j])
while tmp != 0 and tour % 4 == 1:  # 向南
tmp -= 1
i += 1
if 0 <= i < R and 0 <= j < C:
ans.append([i, j])
while tmp != 0 and tour % 4 == 2:  # 向西
tmp -= 1
j -= 1
if 0 <= i < R and 0 <= j < C:
ans.append([i, j])
while tmp != 0 and tour % 4 == 3:  # 向北
tmp -= 1
i -= 1
if 0 <= i < R and 0 <= j < C:
ans.append([i, j])

tour += 1  # 走完step步改变一次方向
cnt += 1  # 转向次数加1

return ans
``````