【LeetCode】面试题29. 顺时针打印数组

题目:

思路:

1、一圈一圈的打印,每次打印一圈,剥洋葱。
2、上下左右四个边界逐次移动。

代码:

Python

class Solution(object):
    def printCircle(self, matrix, x1, x2, y1, y2):
        # 非二维矩阵时特殊处理
        if x1 == x2:
            for i in range(y1, y2 + 1):
                self.result.append(matrix[x1][i])
        elif y1 == y2:
            for i in range(x1, x2 +1):
                self.result.append(matrix[i][y1])
        # 打印当前二维矩阵最外面一圈
        else:
            for i in range(y1, y2 + 1):
                self.result.append(matrix[x1][i])
            for i in range(x1+1, x2+1):
                self.result.append(matrix[i][y2])
            for i in range(y2 - 1,y1-1, -1):
                self.result.append(matrix[x2][i])
            for i in range(x2 -1, x1, -1):
                self.result.append(matrix[i][y1])

    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if len(matrix) == 0:
            return []
        if len(matrix[0]) == 0:
            return []
        self.result = []
        x1 = 0
        y1 = 0
        x2 = len(matrix) - 1
        y2 = len(matrix[0]) - 1
        while x1 <= x2 and y1 <= y2:
            self.printCircle(matrix, x1, x2, y1, y2)
            x1 = x1 + 1
            x2 = x2 - 1
            y1 = y1 + 1
            y2 = y2 -1
        return self.result
class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if len(matrix) == 0 or len(matrix[0]) == 0:
            return []
        res = []
        t = 0
        d = len(matrix) - 1
        l = 0
        r = len(matrix[0]) - 1
        while True:
            for i in range(l, r + 1, 1):
                res.append(matrix[t][i])
            t += 1
            if t > d: break
            for i in range(t, d + 1, 1):
                res.append(matrix[i][r])
            r -= 1
            if r < l: break
            for i in range(r, l - 1, -1):
                res.append(matrix[d][i])
            d -= 1
            if d < t: break
            for i in range(d, t - 1, -1):
                res.append(matrix[i][l])
            l += 1
            if l > r: break
        return res

相关问题

posted @ 2020-06-08 20:06  一只背影  阅读(284)  评论(0编辑  收藏  举报