Rubik's Square

Raj has bought a new Rubik's Cube and he tries to solve it day and night. Seeing this, Vikas tried to help Raj by giving him a problem based on cube Rotation. To make it easier for Raj, As Raj is a beginner Vikas gave a problem in the square matrix instead of a cube. The problem is as follows :

Vikas has an N*N array of different numbers. Now he rotates the rows and columns. Raj has to stay focused and tell Vikas what should be the output of the matrix after R Rows Rotation and C columns rotation.

Raj is now more confused than ever about the above problem. Help him to find the answer.

Note: First all the rows will be rotated and then all the columns will be rotated. Rotation will be from left to right (for Rows) and Top to Bottom (for Column).

Example:

Input:   n = 5, r = 3, c = 4, arr = {{8, 6, 3, 9, 1}, {7, 4, 6, 4, 6}, {3, 4, 2, 0, 4}, {0, 5, 3, 3, 9}, {8, 5, 4, 9, 3}}, row = {5, 2, 1}, col = {4, 5, 5, 4}

Output:

1 8 6 3 9 6 7 4 4 9 3 4 2 3 9 0 5 3 6 4 3 8 5 0 4

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

void print(vector<vector<int>> v)
{
    for (int i = 0i < v.size(); i++)
    {
        for (int j = 0j < v[i].size(); j++)
            cout << v[i][j] << " ";
        cout << "\n";
    }
}

void rubiksSquare(int nint rint c,
                  vector<vector<int>> &arr,
                  vector<int&row,
                  vector<int&col)
{
    for (int i = 0i < ri++)
    {
        int x = row[i];

        int temp = arr[x - 1][n - 1];
        for (int k = n - 2k >= 0k--)
        {
            arr[x - 1][k + 1] = arr[x - 1][k];
        }

        arr[x - 1][0] = temp;
    }

    for (int i = 0i < ci++)
    {
        int x = col[i];

        int temp = arr[n - 1][x - 1];
        for (int k = n - 2k >= 0k--)
        {
            arr[k + 1][x - 1] = arr[k][x - 1];
        }
        arr[0][x - 1] = temp;
    }

    vector<vector<int>> res;
    for (int i = 0i < ni++)
    {
        vector<intv;
        for (int j = 0j < nj++)
        {
            v.push_back(arr[i][j]);
        }
        res.push_back(v);
    }
    print(res);
}
int main()
{
    int n = 5r = 3c = 4;

    vector<vector<int>> arr = {{86391},
                               {74646},
                               {34204},
                               {05339},
                               {85493}};

    vector<introw = {521};

    vector<intcol = {4554};

    rubiksSquare(nrcarrrowcol);

    return 0;
}


No comments:

Post a Comment