Diagonal Traverse II in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of lists called nums, we have to show all elements of nums in diagonal order.

So, if the input is like

then the output will be [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]

To solve this, we will follow these steps −

  • Define an array ret

  • Define one 2D array v

  • for initialize i := 0, when i < size of nums, update (increase i by 1), do −

    • for initialize j := 0, when j < size of nums[i], update (increase j by 1), do −

      • insert { nums[i, j], i, j } at the end of v

  • sort the array v

  • for each it in v, do,

    • insert it[0] at the end of ret

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   static bool cmp(vector <int>& a, vector <int>& b ){
      int sum1 = a[1] + a[2];
      int sum2 = b[1] + b[2];
      return sum1 == sum2 ? a[1] > b[1] : sum1 < sum2;
   }
   vector<int> findDiagonalOrder(vector& nums) {
      vector<int> ret;
      vector<vector<int> > v;
      for (int i = 0; i < nums.size(); i++) {
         for (int j = 0; j < nums[i].size(); j++) {
            v.push_back({ nums[i][j], i, j });
         }
      }
      sort(v.begin(), v.end(), cmp);
      for (auto& it : v)
      ret.push_back(it[0]);
      return ret;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{1,2,3,4,5},{6,7},{8},{9,10,11},{12,13,14,15,16}};
   print_vector(ob.findDiagonalOrder(v));
}

Input

{{1,2,3,4,5},{6,7},{8},{9,10,11},{12,13,14,15,16}}

Output

[1, 6, 2, 8, 7, 3, 9, 4, 12, 10, 5, 13, 11, 14, 15, 16, ]
raja
Updated on 17-Nov-2020 12:08:03

Advertisements