# 498. Diagonal Traverse

对矩阵做Z字型走对角线遍历。根据当前坐标(x, y)用(x + y) % 2 判断是改往上走还是下走。上走时当y撞到N - 1意味着过了中央对角线，该往下进入下一对角线，否则判断x == 0，该往右进入下一对角线，判断顺序不能错；往下走时类似。这里的x和y是指二维数组的维度，和笛卡尔坐标系是反着的，x是竖y是横。

```cpp
/*
 * @lc app=leetcode id=498 lang=cpp
 *
 * [498] Diagonal Traverse
 */

// @lc code=start
class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
        const int M = matrix.size(), N = M == 0 ? 0 : matrix[0].size();
        vector<int> res(M * N, 0);
        for (int i = 0, x = 0, y = 0, c = 0; i < M * N; ++i) {
            res[c++] = matrix[x][y];
            if ((x + y) % 2 == 0) {
                if (y == N - 1) ++x;
                else if (x == 0) ++y;
                else {
                    --x;
                    ++y;
                }
            } else {
                if (x == M - 1) ++y;
                else if (y == 0) ++x;
                else {
                    ++x;
                    --y;
                }
            }
        }
        return res;
    }
};
// @lc code=end


```


---

# 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://hao-fu-1.gitbook.io/oj/array_and_numbers/spiral-matrix/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.
