Diagonal Traverse

Problem Id: 498 Difficulty: Medium


Intuition

Solution


class Solution:
    def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []
        ans = []
        for ij in range(len(matrix) + len(matrix[0]) - 1):
            if ij % 2 == 0:
                i = min(ij, len(matrix) - 1)
                j = ij - i
                while i >= 0 and j < len(matrix[0]):
                    ans.append(matrix[i][j])
                    i -= 1
                    j += 1
            else:
                j = min(ij, len(matrix[0]) - 1)
                i = ij - j
                while i < len(matrix) and j >= 0:
                    ans.append(matrix[i][j])
                    i += 1
                    j -= 1
        return ans