题解 | #对角线遍历矩阵#

对角线遍历矩阵

https://www.nowcoder.com/practice/04b591e3537046c68bf398c18b84cb27

class Solution {
public:
    vector<int> diagonalOrder(vector<vector<int>>& mat) {
        
        vector<int> res;
        if (mat.empty() || mat[0].empty()) return res;
        int n = mat.size(), m = mat[0].size();
        //首先for中的每次的i都是表示mat[x][y] x和y相加的和,所以只需要确定一个就可以知道另外一个
        //当从下面遍历到上面时,x 起始值要么等于i,要么最大也就等于n - 1;  x的最终值要么等于x要么等于0,要么等于 i - m + 1(这种情况就是当遍历到矩形副对角线的下方)
        //从上面遍历同样,知识一个x ++, 一个x--
        for (int i = 0; i < n + m - 1; i ++ ) 
        {
            if (i % 2 == 0)  //偶数对角线
            {
                for (int x = min(i, n - 1); x >= max(0, i - m + 1); x -- )//从下往上遍历
                    res.push_back(mat[x][i - x ]);
            } else 		     //奇数对角线
            {      
                for (int x = max(0,  i - m + 1); x <= min(i, n - 1); x ++ )//从上往下遍历
                    res.push_back(mat[x][i - x]);
            }
        }
        return res;
    }
};

全部评论

相关推荐

美团 客服平台 薪资应该是后端算高的了,我们姑且称为nk了,给3w签字费
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务