<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 {
public:
    vector<pair<int,int>>mov={{-1,1},{1,-1}};
    bool isvalid(int i,int j,int n,int m){
        return i<n and j<m and i>=0 and j>=0;
    }
    void dfs(int i,int j,int n,int m,vector<vector<int>>& vis,vector<vector<int>>& a,vector<int>&ans){
        ans.push_back(a[i][j]);
         for(int k=0;k<2;k++){
                int ii=i+mov[k].first;
                int jj=j+mov[k].second;
                if(isvalid(ii,jj,n,m) and vis[ii][jj]!=1){
                    vis[i][j]=1;
                    dfs(ii,jj,n,m,vis,a,ans);
                }
            }
        return;
    }
    vector<int> findDiagonalOrder(vector<vector<int>>& a) {
        queue<pair<int,int>>q;
        int n = a.size();
        int m = a[0].size();
        int i=0,j=0;
        vector<vector<int>>vis(n,vector<int>(m,0));
        vector<pair<int,int>>f,s;
        for(int i=0;i<m;i++){
            f.push_back({0,i});
        }
        for(int i=1;i<n;i++){
            f.push_back({i,m-1});
        }
        for(int i=0;i<n;i++){
            s.push_back({i,0});
        }
        for(int i=1;i<m;i++){
            s.push_back({n-1,i});
        }
        for(int i=0;i<f.size();i++){
            if(i%2){
                q.push(f[i]);
            }
            else{
                q.push(s[i]);
            }
        }
        //int flg=1;
        vector<int>ans;
        while(!q.empty()){
            int i = q.front().first;
            int j = q.front().second;
            //cout<<i<<' '<<j<<endl;
            q.pop();
            vis[i][j]=1;
            dfs(i,j,n,m,vis,a,ans);            
        }
        return ans;
    }
};
26686