2025-08-25 08:40:44 +0000 UTC

Diagonal Traverse

Code

class Solution:
    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
        res, rows, cols, cur = [], len(mat), len(mat[0]), []
        for i in range(rows + cols):
            if i < rows:
                row, col = i, 0
            else:
                row, col = rows - 1, (i - rows) + 1 
            while row >= 0 and col < cols:
                cur.append(mat[row][col])
                row, col = row - 1, col + 1
            if i % 2 != 0:
                cur.reverse()
            res.extend(cur)
            cur.clear()
        return res