Suggestion for Rotate 2D Array (6.19)

#1

Perhaps the book should mention the possibility of solving 6.19 via linear algebra? Myself and some of the commenters here did it this way instead of the canonical in-place method.

e.g. generate the matrices to translate, rotate 90 degrees and then translate back. The concatenation of these matrices produces quite a simple solution:

vector<vector> MyRotate2DArray(vector<vector> &A)
{
auto result = A;
int dim = A.size();

for (int row = 0; row < dim; ++row)
{
    for (int col = 0; col < dim; ++col)
    {
        int out_row = col;
        int out_col = -row + dim - 1;

        result[out_row][out_col] = A[row][col];
    }
}
return result;

}

Not as efficient as the in-place method obviously, but it felt very natural and it was fun to solve this way.

0 Likes

#2

Thanks I think the most important problem here is that this problem will be trivialized if you can create another array. Also I personally feel the computation of out_col is not easy for me to understand that :stuck_out_tongue:

Anyways, still thanks for your suggestion here.

0 Likes