DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

2 1

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]

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • -105 <= mat[i][j] <= 105

SOLUTION:

class Solution:
    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
        m = len(mat)
        n = len(mat[0])
        op = []
        x, y = 0, 0
        while len(op) != m * n:
            slope = (x + y) & 1
            op.append(mat[y][x])
            dx, dy = (-1, 1) if slope else (1, -1)
            if x + dx < 0 or x + dx >= n or y + dy < 0 or y + dy >= m:
                if slope:
                    if y < m - 1:
                        y += 1
                    else:
                        x += 1
                else:
                    if x < n - 1:
                        x += 1
                    else:
                        y += 1
            else:
                x += dx
                y += dy
        return op
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay