# 498 Diagonal Traverse

## 498. [Diagonal Traverse](https://leetcode.com/problems/diagonal-traverse/description/)

## 1. Question

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

**Example:**

```
Input:

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

Output:
  [1,2,4,7,5,3,6,8,9]

Explanation:
```

![](/files/-LyrLT9ZWn3EkNTFMDU5)

## 2. Implementation

```java
class Solution {
    public int[] findDiagonalOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return new int[0];
        }

        int m = matrix.length, n = matrix[0].length;
        int[] res = new int[m * n];
        int row = 0, col = 0;

        for (int i = 0; i < m * n; i++) {
            res[i] = matrix[row][col];
            // Moving up first
            if ((row + col) % 2 == 0) {
                if (col == n - 1) {
                    ++row;
                }
                else if (row == 0) {
                    ++col;
                }
                else {
                    --row;
                    ++col;
                }
            }
            else {
                if (row == m - 1) {
                    ++col;
                }
                else if (col == 0) {
                    ++row;
                }
                else {
                    ++row;
                    --col;
                }
            }
        }
        return res;
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(mn), 空间复杂度O(mn)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/google/498-diagonal-traverse.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
