#include <cstddef>
#include <vector>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param mat int整型vector<vector<>>
     * @return int整型vector
     */
    vector<int> diagonalOrder(vector<vector<int> >& mat) {
        // write code here
        int count = -1;
        vector<int> ans;
        ans.push_back(mat[0][0]);
        int num = 1;
        //方向数组
        vector<pair<int, int>> dp{{0, 1}, {1, -1}, {1, 0}, {-1, 1}};
        int i = 0, j = 0;
        int m = mat.size();//行数
        int n = mat[0].size();//列数
        //总共要遍历的次数
        while (num < m * n) {
            count = (count + 1) % 4;
            if (count == 0) {
                //右移
                int x ;
                int y ;
                if(j==n-1){//到达最右边特殊处理
                    y=j;
                    x=i +1;
                }else{
                    x = i + dp[count].first;
                    y = j + dp[count].second;
                }
                
                if (x < m && y < n && x >= 0 && y >= 0 ) {
                    ans.push_back(mat[x][y]);
                    i = x;
                    j = y;
                    num++;
                }

            } else if (count == 2) {
                //下移
                int x ;
                int y ;
                if(i==m-1){//到达最下边特殊处理
                    x=i;
                    y=j + 1;
                }else{
                    x = i + dp[count].first;
                    y = j + dp[count].second;
                }
                if (x < m && y < n && x >= 0 && y >= 0 ) {
                    ans.push_back(mat[x][y]);
                    i = x;
                    j = y;
                    num++;
                }
            } else if (count == 3) {
                //斜上方移动
                int x = i + dp[count].first;
                int y = j + dp[count].second;
                while (x < m && y < n && x >= 0 && y >= 0) {
                    ans.push_back(mat[x][y]);
                    i = x;
                    j = y;
                    x = i + dp[count].first;
                    y = j + dp[count].second;
                    num++;
                }
            } else if (count == 1) {
                //斜下方移动
                int x = i + dp[count].first;
                int y = j + dp[count].second;
                while (x < m && y < n && x >= 0 && y >= 0) {
                    ans.push_back(mat[x][y]);
                    i = x;
                    j = y;
                    x = i + dp[count].first;
                    y = j + dp[count].second;
                    num++;
                }
            }
            
        }

        return ans;
    }
};