0

I am trying to rotate a 2d vector clockwise but I am unable to get it to work for vectors that are not square.

Here is what I tried

 bool Pgm::Clockwise(){
    int i, j, k;
    vector <vector <int> > tempPixel;
    for (i = 0; i < Pixels.size(); i++) {
        tempPixel.push_back(Pixels.at(i));
    }

    for (j = 0; j < tempPixel.size(); j++) {
        tempPixel.push_back(vector<int>());
        for (k = 0; k < tempPixel.at(0).size(); k++) {
            tempPixel.at(j).push_back(Pixels.at(j));
        }
    }

    return true;
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
codeblue
  • 23
  • 5

1 Answers1

1
#include <vector>

std::vector<std::vector<int>> rotateClockwise(std::vector<std::vector<int>> v) {
    int n = v.size();
    int m = v[0].size();

    // create new vector with swapped dimensions
    std::vector<std::vector<int>> rotated(m, std::vector<int>(n));

    // populate the new vector
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            rotated[j][n-i-1] = v[i][j];
        }
    }

    return rotated;
}

This function takes a 2D vector as input and returns a new 2D vector that is rotated 90 degrees clockwise. It first creates a new vector rotated with dimensions swapped, then populates it by copying the elements from the input vector in the appropriate order. i hope this will help you to get an idea..

K K Jangid
  • 19
  • 2