C++ Easy to Understand


  • 1
    /* We can extend the logic of Next Greater Element I to solve this. Here, I create another vector findNums for the same. This isn't necessary but makes the extension easier to understand.*/
    
    class Solution {
        public:
        vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
            vector<int> res;
            int backward = 0;         // move up
            int n = matrix.size();    // number of rows
            if(n == 0) return res;
            int m = matrix[0].size(); // number of columns
            int count = 0;
            int i=0, j=0;
            while(count<m*n)
            {
                if(backward==0)
                {
                    res.push_back(matrix[i][j]);
                    j++;
                    i--;
                    if(i < 0 && j <= m-1) {i++; backward = 1;}
                    else if(j > m-1) {i = i+2; j = m-1; backward = 1;}
                }
                else
                {
                    res.push_back(matrix[i][j]);
                    j--;
                    i++;
                    if(j < 0 && i <= n-1) {j++; backward = 0;}
                    else if(i > n-1) {j = j+2; i = n-1; backward = 0;}
                }
                count++;
            }
            return res;
        }
    };

Log in to reply
 

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