498. Diagonal Traverse
Description
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]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-105 <= mat[i][j] <= 105
Solution
diagonal-traverse.py
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix: return []
R,C = len(matrix), len(matrix[0])
mp = collections.defaultdict(collections.deque)
for i in range(R):
for j in range(C):
if (i + j) % 2 == 0:
mp[i+j].appendleft(matrix[i][j])
else:
mp[i+j].append(matrix[i][j])
return [c for key in mp for c in mp[key]]