Diagonal Traverse

先是左边变换方向的方法,思路直接,但是代码很丑,而且个人现在也没想到什么办法能改进

class Solution(object):
    def findDiagonalOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        n = len(matrix)
        if not n:
            return []

        m = len(matrix[0])
        if not m:
            return []

        curRow, curCol = 0, 0
        count = 0
        result = []
        while count < n + m - 1:
            if count % 2 == 0:
                while curRow - 1 >= 0 and curCol + 1 < m:
                    result.append(matrix[curRow][curCol])
                    curRow -= 1
                    curCol += 1
                result.append(matrix[curRow][curCol])
                if curCol != m - 1:
                    curCol += 1
                else:
                    curRow += 1
            else:
                while curRow + 1 < n and curCol - 1 >= 0:
                    result.append(matrix[curRow][curCol])
                    curRow += 1
                    curCol -= 1
                result.append(matrix[curRow][curCol])
                if curRow != n - 1:
                    curRow += 1
                else:
                    curCol += 1

            count += 1
        return result

这里还有一种不太需要关心方向变换的方法,即按照对角线平推,每次利用当前层的坐标推出下一层的坐标,最后把奇数行反转,这种需要利用额外空间,但是代码肯定比上面这种好看的多

results matching ""

    No results matching ""