Home

Twisted Matrix

A matrix of the same rows and same columns is given. Sort the matrix in such a manner that she will start from the first element and traverse the matrix in a clockwise manner at the end she should be at the middle position with the largest element. Find the sorted matrix.

Example:

Input:  n = 3, arr={{2,5,12},{22,45,55},{1,6,8}}

Output:

1 2 5 45 55 6 22 12 8

Approach

C++

#include <bits/stdc++.h>
using namespace std;
int l;
void twistedMatrix(vector<vector<int>> &arrint i
int jint mint nvector<intv)
{
    if (i >= m || j >= n)
        return;
    for (int p = ip < np++)
        arr[i][p] = v[l++];
    for (int p = i + 1p < mp++)
        arr[p][n - 1] = v[l++];
    if ((m - 1) != i)
        for (int p = n - 2p >= jp--)
            arr[m - 1][p] = v[l++];
    if ((n - 1) != j)
        for (int p = m - 2p > ip--)
            arr[p][j] = v[l++];
    twistedMatrix(arri + 1j + 1m - 1n - 1v);
}
int main()
{
    int n = 3;
    vector<vector<int>> arr = {{2512},
                               {224555},
                               {168}};
    vector<intv;
    for (int i = 0i < ni++)
    {
        for (int j = 0j < nj++)
        {
            v.push_back(arr[i][j]);
        }
    }
    l = 0;
    sort(v.begin(), v.end());
    twistedMatrix(arr00nnv);
    for (int i = 0i < ni++)
    {
        for (int j = 0j < nj++)
            cout << arr[i][j] << " ";
        cout << "\n";
    }
    return 0;
}


No comments:

Post a Comment