
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Diagonal Traverse II in C++
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 −
#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, ]
- Related Articles
- Diagonal Traverse in C++
- How to traverse a C++ set in reverse direction?
- Count the number of ways to traverse a Matrix in C++
- Traverse through a HashMap in Java
- Traverse through a HashSet in Java
- Swap Upper diagonal with Lower in C++
- Diagonal of a Regular Heptagon in C++?
- Diagonal of a Regular Pentagon in C++?
- Diagonal Traversal of Binary Tree in C++?
- How to traverse Hierarchical data in Oracle?
- Traverse TreeSet elements in descending order in java
- Zigzag (or diagonal) traversal of Matrix in C++
- Diagonal of a Regular Hexagon in C++?\n
- Diagonal Sum of a Binary Tree in C++?
- Find length of Diagonal of Hexagon in C++

Advertisements