C++ Simple Solution


  • 0
    class Solution {
    public:
        vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
            vector<int> ret;
            if (matrix.empty() || matrix[0].empty())
                return ret;
            int r = 0, c = 0, m = matrix.size(), n = matrix[0].size();
            vector<pair<int, int>> next = {{-1, 1}, {1, -1}};
            int f = 0;
            while (1) {
                ret.push_back(matrix[r][c]);
                if (r == m - 1 && c == n - 1)
                    return ret;
                if (r == 0 && c < n - 1 && f == 0) {
                    f = 1;
                    c++;
                } else if (c == n - 1 && f == 0) {
                    f = 1;
                    r++;
                } else if (f == 1 && r == m - 1) {
                    f = 0;
                    c++;
                } else if (f == 1 && r > 0 && c == 0) {
                    f = 0;
                    r++;
                } else {
                    r += next[f].first;
                    c += next[f].second;
                }
            }
            return ret;
        }
    };
    

Log in to reply
 

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