# 498. Diagonal Traverse
Given an m x n
matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
# Solution
Approach 1: track directions.
# Code (Python)
Approach 1:
class Solution:
def findDiagonalOrder(self, mat: list[list[int]]) -> list[int]:
if not mat or not mat[0]:
return []
result = []
row, col = 0, 0
height, width = len(mat), len(mat[0])
is_up = True
while len(result) < height * width:
result.append(mat[row][col])
if is_up:
if not (row - 1 >= 0 and col + 1 < width):
is_up = not is_up
if not is_up:
if col + 1 < width:
col += 1
else:
row += 1
continue
row -= 1
col += 1
else:
if not (row + 1 < height and col - 1 >= 0):
is_up = not is_up
if is_up:
if row + 1 < height:
row += 1
else:
col += 1
continue
row += 1
col -= 1
return result
# Code (C++)
Approach 1:
Approach 2: