498. Diagonal Traverse

https://leetcode.com/problems/diagonal-traverse/description/

对矩阵做Z字型走对角线遍历。根据当前坐标(x, y)用(x + y) % 2 判断是改往上走还是下走。上走时当y撞到N - 1意味着过了中央对角线,该往下进入下一对角线,否则判断x == 0,该往右进入下一对角线,判断顺序不能错;往下走时类似。这里的x和y是指二维数组的维度,和笛卡尔坐标系是反着的,x是竖y是横。

/*
 * @lc app=leetcode id=498 lang=cpp
 *
 * [498] Diagonal Traverse
 */

// @lc code=start
class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
        const int M = matrix.size(), N = M == 0 ? 0 : matrix[0].size();
        vector<int> res(M * N, 0);
        for (int i = 0, x = 0, y = 0, c = 0; i < M * N; ++i) {
            res[c++] = matrix[x][y];
            if ((x + y) % 2 == 0) {
                if (y == N - 1) ++x;
                else if (x == 0) ++y;
                else {
                    --x;
                    ++y;
                }
            } else {
                if (x == M - 1) ++y;
                else if (y == 0) ++x;
                else {
                    ++x;
                    --y;
                }
            }
        }
        return res;
    }
};
// @lc code=end

Last updated