Leetcode 498.对角线遍历

int d[2][2]={-1,1,1,-1};
//  -1  1       
//  1  -1
class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
        vector<int> ans;
        int m=mat.size(),n=mat[0].size();
        int i=0,j=0;
        bool pos=0;
        int test=0;   //
        while (!(i==m-1&&j==n-1)){
            test++;
            ans.push_back(mat[i][j]);
            i+=d[pos][0],j+=d[pos][1];
            if (!(i>=0&&i<m&&j>=0&&j<n)){
//                ans.push_back(pos);
                if (pos){
                    j++;
                    if (!(i>=0&&i<m&&j>=0&&j<n))
                        j++,i--;
                }
                else{
                    i++;
                    if (!(i>=0&&i<m&&j>=0&&j<n))
                        i++,j--;
                }
                if (pos)
                    pos=false;
                else
                    pos=true;
            }
        }
        ans.push_back(mat[m-1][n-1]);
        return ans;
    }
};

 

 

posted @ 2022-06-14 22:35  wegret  阅读(21)  评论(0)    收藏  举报