Share my concise c++ solution


  • 0
    Z
    class Solution {
    public:
        vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
            if (matrix.empty() || matrix[0].empty()) return {};
            int m = matrix.size(), n = matrix[0].size();
            vector<int> res(m * n);
            for (int k = 0, i = 0, j = 0; i + j <  m + n - 1; ++k) {
                res[k] = matrix[i][j];
                if ((i + j) % 2) {
                    if (i == m - 1) ++j;
                    else if (j == 0) ++i;
                    else {++i;--j;}
                } else {
                    if (j == n - 1) ++i;
                    else if (i == 0) ++j;
                    else {--i;++j;}
                }
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.