[] Array Leetcode coil matrix (54)

topic

Given a matrix of mxn elements (m row, n-column), follow a helical clockwise order, returns all the elements in the matrix.

Example 1:

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

Example 2:

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

answer

Like search, the definition of an array of moving up and down about representation. The amount of code can cry Liaoning ...

z = [
            [0, 1],  # 右
            [1, 0],  # 下
            [0, -1],  # 左
            [-1, 0]  # 上
        ]

Code:

class Solution:
    # Time: O(N),N为数值个数
    def spiralOrder(self, matrix):
        if not matrix:
            return []
        ans = []
        Y, X = len(matrix[0]), len(matrix)
        z = [
            [0, 1],  # 右
            [1, 0],  # 下
            [0, -1],  # 左
            [-1, 0]  # 上
        ]
        x = y = 0
        while len(ans) != X * Y:
            if matrix[x][y] != float('-inf'):
                ans.append(matrix[x][y])
                matrix[x][y] = float('-inf')
            while x + z[0][0] < X and y + z[0][1] < Y and matrix[x + z[0][0]][y + z[0][1]] != float('-inf'):  # 向右
                x = x + z[0][0]
                y = y + z[0][1]
                if matrix[x][y] != float('-inf'):
                    ans.append(matrix[x][y])
                    matrix[x][y] = float('-inf')
            while x + z[1][0] < X and y + z[1][1] < Y and matrix[x + z[1][0]][y + z[1][1]] != float('-inf'):  # 向下
                x = x + z[1][0]
                y = y + z[1][1]
                if matrix[x][y] != float('-inf'):
                    ans.append(matrix[x][y])
                    matrix[x][y] = float('-inf')
            while x + z[2][0] < X and y + z[2][1] < Y and matrix[x + z[2][0]][y + z[2][1]] != float('-inf'):  # 向左
                x = x + z[2][0]
                y = y + z[2][1]
                if matrix[x][y] != float('-inf'):
                    ans.append(matrix[x][y])
                    matrix[x][y] = float('-inf')
            while x + z[3][0] < X and y + z[3][1] < Y and matrix[x + z[3][0]][y + z[3][1]] != float('-inf'):  # 向上
                x = x + z[3][0]
                y = y + z[3][1]
                if matrix[x][y] != float('-inf'):
                    ans.append(matrix[x][y])
                    matrix[x][y] = float('-inf')
        return ans


s = Solution()
print(s.spiralOrder([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]))   

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

Guess you like

Origin www.cnblogs.com/ldy-miss/p/12122617.html