[leetcode] Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

思路:循環遍歷,當遍歷一邊外圈的時候,把左上角座標和左下角座標轉換爲內圈的左上角和左下角,特別考慮只有一行或者一列的情況

class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of integers
    def spiralOrder(self, matrix):
        if len(matrix) == 0:
            return []
        result = []
        x1 = 0
        y1 = 0
        x2 = len(matrix[0]) - 1
        y2 = len(matrix) - 1
        while x1 <= x2 and y1 <= y2:
            if x1 == x2:
                for i in range(y1, y2+1):
                    result.append(matrix[i][x1])
                break
            if y1 == y2:
                for i in range(x1, x2+1):
                    result.append(matrix[y1][i])
                break
            for i in range(x1, x2):
                result.append(matrix[y1][i])
            for i in range(y1, y2):
                result.append(matrix[i][x2])
            for i in range(x1+1, x2+1)[::-1]:
                result.append(matrix[y2][i])
            for i in range(y1+1, y2+1)[::-1]:
                result.append(matrix[i][x1])
            if x2 - x1 == 1 or y2 - y1 == 1:
                break
            x1 += 1
            y1 += 1
            x2 -= 1
            y2 -= 1
        return result


發佈了33 篇原創文章 · 獲贊 0 · 訪問量 7212
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章