Wednesday, March 3, 2021

Published March 03, 2021 by Anonymous with 0 comment

Modify a given matrix by placing sorted boundary elements in clockwise manner

#include <bits/stdc++.h>

using namespace std;

  

void printMatrix(vector<vector<int> > a)

{

    for (auto x : a) {

        for (auto y : x) {

            cout << y << " ";

        }

        cout << "\n";

    }

}

  

void sortBoundaryWise(vector<vector<int> > a)

{

    

        

        

        

        

      

    int i, k = 0, l = 0;

    int m = a.size(), n = a[0].size();

    int n_i, n_k = 0, n_l = 0, n_m = m, n_n = n;

  

    while (k < m && l < n) {

  

        

        

        vector<int> boundary;

  

        

        for (i = l; i < n; ++i) {

            boundary.push_back(a[k][i]);

        }

        k++;

  

        

        for (i = k; i < m; ++i) {

            boundary.push_back(a[i][n - 1]);

        }

        n--;

  

        

        if (k < m) {

            for (i = n - 1; i >= l; --i) {

                boundary.push_back(a[m - 1][i]);

            }

            m--;

        }

  

        

        if (l < n) {

            for (i = m - 1; i >= k; --i) {

                boundary.push_back(a[i][l]);

            }

            l++;

        }

  

        

        sort(boundary.begin(), boundary.end());

        int ind = 0;

  

        

        

  

        

        for (i = n_l; i < n_n; ++i) {

            a[n_k][i] = boundary[ind++];

        }

        n_k++;

  

        

        for (i = n_k; i < n_m; ++i) {

            a[i][n_n - 1] = boundary[ind++];

        }

        n_n--;

  

        

        if (n_k < n_m) {

            for (i = n_n - 1; i >= n_l; --i) {

                a[n_m - 1][i] = boundary[ind++];

            }

            n_m--;

        }

  

        

        if (n_l < n_n) {

            for (i = n_m - 1; i >= n_k; --i) {

                a[i][n_l] = boundary[ind++];

            }

            n_l++;

        }

    }

  

    

    printMatrix(a);

}

  

int main()

{

    

    vector<vector<int> > matrix = { { 9, 7, 4, 5 },

                                    { 1, 6, 2, -6 },

                                    { 12, 20, 2, 0 },

                                    { -5, -6, 7, -2 } };

  

    sortBoundaryWise(matrix);

  

    return 0;

}

Let's block ads! (Why?)

      edit

0 comments:

Post a Comment