螺旋打印矩阵

    科技2022-07-12  130

    思路:

    使用Col1和Row1变量记录左上角坐标,使用Col2和Row2变量记录右下角坐标,

    两个角固定了这个矩阵,设置初始值CurR=0,CurC=0,从左上角开始,然后分四部分打印一圈:

    当CurC<Col2时,打印并CurC++

    当CurR<Row2时,打印并CurR++

    当CurC>Col1时,打印并CurC--

    当CurR>Row1时,打印并CurR--

    注意打印时考虑特例一行或一列的情况

    在大循环中,每次打完一圈以后,左上坐标向右下角移动一格,右下坐标向左上角移动一格,循环退出时即左上角坐标跑到了右下角坐标的下面。

    lass Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix: return [] res = [] Col1, Row1 = 0, 0 Col2, Row2 = len(matrix[0])-1, len(matrix)-1 res = [] while Col1 <= Col2 and Row1 <= Row2: self.Printmatrix(res, matrix, Row1, Col1, Row2, Col2) Row1 += 1 Col1 += 1 Row2 -= 1 Col2 -= 1 return res def Printmatrix(self, res, matrix, Row1, Col1, Row2, Col2): if Row1 == Row2: while Col1 <= Col2: res.append(matrix[Row1][Col1]) Col1 += 1 elif Col1 == Col2: while Row1 <= Row2: res.append(matrix[Row1][Col1]) Row1 += 1 else: curR = Row1 curC = Col1 while curC < Col2: res.append(matrix[curR][curC]) curC += 1 while curR < Row2: res.append(matrix[curR][curC]) curR += 1 while curC > Col1: res.append(matrix[curR][curC]) curC -= 1 while curR > Row1: res.append(matrix[curR][curC]) curR -= 1

     

    Processed: 0.013, SQL: 8