Description Given a matrix of m x n size (m rows, n columns), return all elements of the matrix in spiral order. Example 1 input: [[1, 2, 3], [4 and 6], [7,8,9]] to copy the return value: copy,2,3,6,9,8,7,4,5 [1]Copy the code
Answer:
- When there is only one row or column, access all of them directly
- If there is more than one row and more than one column, the access order is left-right, up-down, right-left, down-up
- Pay particular attention to the scope of the access index
Def spiralOrder(self, matrix): def spiralOrder(self, matrix) # write code here if len(matrix)==0: return [] left=0 right=len(matrix[0])-1 top=0 down=len(matrix)-1 res=[] while left<=right and top<=down: if top==down: #one line for ele in matrix[top][left:right+1]: res.append(ele) break elif left==right: # one colomn for row in matrix[top:down+1]: res.append(row[left]) break else: # left-right; top-down; right-left; down-top for ele in matrix[top][left:right]: res.append(ele) for row in matrix[top:down]: res.append(row[right]) for ele in matrix[down][right:left:-1]: res.append(ele) for row in matrix[down:top:-1]: res.append(row[left]) top=top+1 right=right-1 down=down-1 left=left+1 return resCopy the code