sagelearnai

Diagonal Traverse

Difficulty: Medium · Pattern: Matrix · LeetCode #498

Return all elements of an m × n matrix in diagonal zigzag order: up-right along the first anti-diagonal, down-left along the next, and alternating from there.

Example

text
[[1,2,3],
 [4,5,6],     →  [1,2,4,7,5,3,6,8,9]
 [7,8,9]]

Hints

  1. All cells on one anti-diagonal share r + c = d.
  2. Diagonals with even d are read bottom-to-top (going up-right), and odd ones top-to-bottom.

Approach

For d from 0 to m + n − 2, the rows on the diagonal run from max(0, d − n + 1) to min(d, m − 1). Collect mat[r][d − r] top-to-bottom, and reverse the list if d is even.

Grouping by r + c (anti-diagonals) or by r − c (diagonals) is the key trick for every diagonal-iteration problem, including the N-Queens diagonal checks.

Complexity

Time: O(m·n). Space: O(min(m, n)) per diagonal besides the output.

Python solution
def findDiagonalOrder(mat):
    m, n = len(mat), len(mat[0])
    res = []
    for d in range(m + n - 1):
        diag = [mat[r][d - r] for r in range(max(0, d - n + 1), min(d, m - 1) + 1)]
        res += diag[::-1] if d % 2 == 0 else diag
    return res
JavaScript solution
function findDiagonalOrder(mat) {
  const m = mat.length, n = mat[0].length, res = [];
  for (let d = 0; d < m + n - 1; d++) {
    const diag = [];
    for (let r = Math.max(0, d - n + 1); r <= Math.min(d, m - 1); r++) diag.push(mat[r][d - r]);
    if (d % 2 === 0) diag.reverse();
    res.push(...diag);
  }
  return res;
}