leetcode – spiral matrix

问题:

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

array = [[1, 2, 3, 4], 
         [5, 6, 7, 8], 
         [9, 10, 11, 12],
         [13, 14, 15, 16 ]
        ]

Output:

[1,2,3,4,8,12,11,10,9,5,6,7]

解答:

  1. 首先确定行列的边界值, startRow,endRow,startCol,endCol
  2. 按照题目的要求进行螺旋便利 , 分别向右, 向下, 向左, 向上移动,对应四个循环。
  3. 特殊情况检查, 当出现单行或者单列的情况,在向左或向上遍历前, 分别检查行或列的边界值是否相等, startRow == endRow 或 startCol == endCol , 相等则停止遍历。
def spiralTraverse(array):
    # Write your code here.
    result = []
    startRow , endRow = 0, len(array) - 1
    startCol, endCol = 0, len(array[0]) - 1

    while startRow <= endRow and startCol <= endCol:
        # right col 
        for col in range(startCol, endCol + 1):
            result.append(array[startRow][col])

        # down row
        for row in range(startRow + 1, endRow + 1):
            result.append(array[row][endCol])

        # left  col reversed
        for col in reversed(range(startCol, endCol)):
            if startRow == endRow:
                break;
            result.append(array[endRow][col])

        # up   row reversed
        for row in reversed(range(startRow+1, endRow)):
            if startCol == endCol:
                break;
            result.append(array[row][startCol])
        
        startRow = startRow + 1
        endRow = endRow -1
        startCol = startCol + 1
        endCol = endCol - 1

    return result

 

图片及引用

图片from李進生

https://www.algoexpert.io/questions/spiral-traverse

 

 

 

Comments are closed.