r2dv.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // If you suddenly need values from a 2D
  2. // array diagonally and clearing it,
  3. // this function is for You
  4. //
  5. // The Ripper of 2d vectors
  6. //
  7. // r2dv.cpp
  8. //
  9. // Created by Volkov Roman on 19.03.2023.
  10. //
  11. #include <stdio.h>
  12. #include <vector>
  13. using namespace std;
  14. vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
  15. vector<int> result;
  16. int i=0, j=0, x=0, y=0;
  17. x = nums.size();
  18. for (i=0; i<x; ++i) {
  19. if (nums[i].size() > y) {
  20. y = nums[i].size();
  21. }
  22. }
  23. const int iters_summ = x + y - 1;
  24. int max=0;
  25. for (i=0; i < iters_summ; i++){
  26. j = i;
  27. if (i > x-1){
  28. max = x;
  29. j = x-1;
  30. } else {
  31. max++;
  32. }
  33. int j0;
  34. for (j0=max; j0>0; j0--){
  35. if (nums[j].empty()){
  36. j--;
  37. continue;
  38. }
  39. result.push_back(nums[j][0]);
  40. nums[j].erase(nums[j].begin());
  41. j--;
  42. }
  43. }
  44. return result;
  45. }
  46. int main() {
  47. /*
  48. vector < vector <int> > ivector = {{1,3,6,8},
  49. {2,5},
  50. {4,7}};
  51. vector<int> test = findDiagonalOrder(ivector);
  52. for (int i=0; i < test.size(); i++) {
  53. //12435768
  54. cout << test[i] << "";
  55. }
  56. cout << endl;
  57. cout << "Ivector size: " << ivector.size() << endl; //3
  58. for (int i=0; i < ivector.size(); i++) {
  59. //124357689
  60. cout << "Ivector[" <<i << "] Size: " << ivector[i].size() << endl;
  61. // Ivector[0] Size: 0
  62. // Ivector[1] Size: 0
  63. // Ivector[2] Size: 0
  64. }
  65. */
  66. return 0;
  67. }