c++ clean solution with explanations


  • 0
    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
            int m = matrix.size(), n;
            if(m!=0)n = matrix[0].size();
            vector<int> vec;
            int i=0, j=0, dir = 1; //dir=1 means move right-up, dir = 0 means move bottom-left
            while(i<m && j<n && i>=0 && j>=0){
                vec.push_back(matrix[i][j]);
                if(i==m-1&&j==n-1)break;
                if(dir){
                    if(i-1>=0&&j+1<n){i--,j++;}  //move right-up
                    else if(j+1<n){j++,dir = 0;}  // move right
                    else {i++,dir = 0;}  //move down
                }
                else{
                    if(i+1<m && j-1>=0){i++,j--;}  //move bottom-left
                    else if(i+1<m){i++, dir = 1;}  //move down
                    else {j++,dir = 1;} //move right
                }
            }
            return vec;
        }
    

Log in to reply
 

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