<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg" style="width: 334px; height: 334px;" />
<pre>
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> [1,2,4,7,5,3,6,8,9]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]]
<strong>Output:</strong> [1,2,3,4]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == mat.length</code></li>
	<li><code>n == mat[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>5</sup> &lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution {
private:
    int dx[2] = {-1, 1};
    int dy[2] = {1, -1};
    int direction = 0;
    vector<int> result;
    vector<vector<int>> mat;

    bool isValid(int x, int y) {
        return x >= 0 && x < mat.size() && 
            y >= 0 && y < mat[x].size();
    }

    pair<int, int> transition(int x, int y) {
        vector<int> ddx, ddy;
        if (direction == 0) {
            ddx = {0, 1};
            ddy = {1, 0};
        }
        else {
            ddx = {1, 0};
            ddy = {0, 1};
        }
        direction = (1 + direction) % 2;

        for (int i = 0; i < 2; i++) {
            int newX = x + ddx[i];
            int newY = y + ddy[i];
            if (isValid(newX, newY))
                return {newX, newY};
        }
        return {-1, -1};
    }

    void traverse(int x, int y) {
        result.push_back(mat[x][y]);

        int newX = x + dx[direction];
        int newY = y + dy[direction];
        if (isValid(newX, newY))
            traverse(newX, newY);
        else {
            auto pair = transition(x, y);
            if (pair.first != -1)
                traverse(pair.first, pair.second);
        }
    }
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
        this->mat = mat;
        traverse(0, 0);
        return result;
    }
};
28681