動機

評語同48

Problem

Given an m x n matrix, return all elements of the matrix in spiral order.

 

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]Output: [1,2,3,4,8,12,11,10,9,5,6,7]

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Sol

處理matrix的走訪,要先確定

  1. 怎樣才算走一圈
  2. 每一圈的長度是多少,怎麼算出來
  3. 每一圈的起點是多少

分兩邊右上與左下,之後就是依照長度去塞

class Solution:
    def spiralOrder(self, ms: List[List[int]]) -> List[int]:
        a,b,ret = len(ms), len(ms[0]), []
        for i in range((min(a,b)+1)//2):
            ret.append(ms[i][i])
            for j in range(i+1,i+b):
                ret.append(ms[i][j])
            for ii in range(i+1,i+a):
                ret.append(ms[ii][i+b-1])
            if a > 1 and b > 1:
                for j in reversed(range(i,i+b-1)):
                    ret.append(ms[i+a-1][j])
                for ii in reversed(range(i+1,i+a-1)):
                    ret.append(ms[ii][i])
            a,b = a-2, b-2
        return ret