GeeksforGeeks App
Open App
Browser
Continue

# Shuffle the given Matrix K times by reversing row and columns alternatively in sequence

Given a matrix arr[][] of size M * N, where M is the number of rows and N is the number of columns, and an integer K. The task is to shuffle this matrix in K steps such that in each step, the rows and columns of the matrix are reversed alternatively i.e start with reversing the 1st row first step, then the 1st column in the second step, then the 2nd row in the third step and so on.

Note: If K exceeds the M or N then reversal starts from the first row or column again.

Examples:

Input: arr[][] = {{3,   4,   1,   8},
{11, 23, 43, 21},
{12, 17, 65, 91},
{71, 56, 34, 24}}
K = 4
Output: {{71, 56, 4, 3},
{21, 17, 23, 12},
{11, 43, 65, 91},
{8, 1, 34, 24}}
Explanation: Steps to be followed:
Reverse the first row
Reverse the first column
Reverse the second row
Reverse the second column

Input: arr[][] = {{11, 23, 43, 21},
{12, 17, 65, 91},
{71, 56, 34, 24}}
K = 8
Output: {{11, 43, 56, 21},
{91, 65, 17, 12},
{24, 34, 23, 71}}

Approach: The problem can be solved by simply running two loops for traversing rows and columns alternatively, till K becomes 0. In the end, print the resultant matrix. Follow the steps mentioned below:

• Run a loop for traversing the matrix.
• In each iteration reverse the proper row and column.
• Do this operation K times.
• Print the final loop.

Below is the implementation of the above approach

## C++

 `// C++ code to implement the above approach``#include ``using` `namespace` `std;``const` `int` `M = 3;``const` `int` `N = 4;` `// Print matrix elements``void` `showArray(``int` `arr[][N])``{``    ``for` `(``int` `i = 0; i < M; i++) {``        ``for` `(``int` `j = 0; j < N; j++)``            ``cout << arr[i][j] << ``" "``;``        ``cout << endl;``    ``}``}` `// Function to shuffle matrix``void` `reverseAlternate(``int` `arr[][N], ``int` `K)``{``    ``int` `turn = 0;``    ``int` `row = 0, col = 0;``    ``while` `(turn < K) {``        ` `        ``// Reverse the row``        ``if` `(turn % 2 == 0) {``            ``int` `start = 0, end = N - 1, temp;``            ``while` `(start < end) {``                ``temp = arr[row % M][start];``                ``arr[row % M][start] =``                    ``arr[row % M][end];``                ``arr[row % M][end] = temp;``                ``start += 1;``                ``end -= 1;``            ``}``            ``row++;``            ``turn++;``        ``}``        ` `        ``// Reverse the column``        ``else` `{``            ``int` `start = 0, end = M - 1, temp;``            ``while` `(start < end) {``                ``temp = arr[start][col % N];``                ``arr[start][col % N] =``                    ``arr[end][col % N];``                ``arr[end][col % N] = temp;``                ``start += 1;``                ``end -= 1;``            ``}``            ``col++;``            ``turn++;``        ``}``    ``}``}` `// Driver code``int` `main()``{` `    ``int` `matrix[M][N] = { { 11, 23, 43, 21 },``                         ``{ 12, 17, 65, 91 },``                         ``{ 71, 56, 34, 24 } };``    ``int` `K = 8;``    ``reverseAlternate(matrix, K);``    ``showArray(matrix);``    ``return` `0;``}`

## Java

 `// Java code to implement the above approach``import` `java.io.*;` `class` `GFG {` `  ``public` `static` `int` `M = ``3``;``  ``public` `static` `int` `N = ``4``;` `  ``// Print matrix elements``  ``public` `static` `void` `showArray(``int` `arr[][])``  ``{``    ``for` `(``int` `i = ``0``; i < M; i++) {``      ``for` `(``int` `j = ``0``; j < N; j++)``        ``System.out.print(arr[i][j] + ``" "``);``      ``System.out.println();``    ``}``  ``}` `  ``// Function to shuffle matrix``  ``public` `static` `void` `reverseAlternate(``int` `arr[][], ``int` `K)``  ``{``    ``int` `turn = ``0``;``    ``int` `row = ``0``, col = ``0``;``    ``while` `(turn < K) {` `      ``// Reverse the row``      ``if` `(turn % ``2` `== ``0``) {``        ``int` `start = ``0``, end = N - ``1``, temp;``        ``while` `(start < end) {``          ``temp = arr[row % M][start];``          ``arr[row % M][start] =``            ``arr[row % M][end];``          ``arr[row % M][end] = temp;``          ``start += ``1``;``          ``end -= ``1``;``        ``}``        ``row++;``        ``turn++;``      ``}` `      ``// Reverse the column``      ``else` `{``        ``int` `start = ``0``, end = M - ``1``, temp;``        ``while` `(start < end) {``          ``temp = arr[start][col % N];``          ``arr[start][col % N] =``            ``arr[end][col % N];``          ``arr[end][col % N] = temp;``          ``start += ``1``;``          ``end -= ``1``;``        ``}``        ``col++;``        ``turn++;``      ``}``    ``}``  ``}` `  ``// Driver code``  ``public` `static` `void` `main (String[] args)``  ``{` `    ``int` `matrix[][] = { { ``11``, ``23``, ``43``, ``21` `},``                      ``{ ``12``, ``17``, ``65``, ``91` `},``                      ``{ ``71``, ``56``, ``34``, ``24` `} };``    ``int` `K = ``8``;``    ``reverseAlternate(matrix, K);``    ``showArray(matrix);``  ``}``}` `// This code is contributed by Shubham Singh`

## Python3

 `# Python code to implement the above approach``M ``=` `3``N ``=` `4` `# Print matrix elements``def` `showArray(arr):``    ` `    ``for` `i ``in` `range``(M):``        ``for` `j ``in` `range``(N):``            ``print``(arr[i][j], end``=` `" "``)``        ``print``()` `# Function to shuffle matrix``def` `reverseAlternate(arr, K):``    ` `    ``turn ``=` `0``    ``row ``=` `0``    ``col ``=` `0``    ``while` `(turn < K):``        ` `        ``# Reverse the row``        ``if` `(turn ``%` `2` `=``=` `0``):``            ``start ``=` `0``            ``end ``=` `N ``-` `1``            ``temp ``=` `0``            ``while` `(start < end):``                ``temp ``=` `arr[row ``%` `M][start]``                ``arr[row ``%` `M][start] ``=` `arr[row ``%` `M][end]``                ``arr[row ``%` `M][end] ``=` `temp``                ``start ``+``=` `1``                ``end ``-``=` `1``            ` `            ``row ``+``=` `1``            ``turn ``+``=` `1``        ` `        ``#Reverse the column``        ``else``:``            ``start ``=` `0``            ``end ``=` `M ``-` `1``            ``temp ``=` `0``            ``while` `(start < end):``                ``temp ``=` `arr[start][col ``%` `N]``                ``arr[start][col ``%` `N] ``=` `arr[end][col ``%` `N]``                ``arr[end][col ``%` `N] ``=` `temp``                ``start ``+``=` `1``                ``end ``-``=` `1``                ` `            ``col ``+``=` `1``            ``turn ``+``=` `1``            ` `# Driver code``matrix ``=` `[[``11``, ``23``, ``43``, ``21``] ,``            ``[``12``, ``17``, ``65``, ``91``] ,``            ``[``71``, ``56``, ``34``, ``24``]]``K ``=` `8``reverseAlternate(matrix, K)``showArray(matrix)``        ` `# This code is contributed by Shubham Singh`

## C#

 `// C# code to implement the above approach``using` `System;` `class` `GFG {` `  ``public` `static` `int` `M = 3;``  ``public` `static` `int` `N = 4;` `  ``// Print matrix elements``  ``public` `static` `void` `showArray(``int``[, ] arr)``  ``{``    ``for` `(``int` `i = 0; i < M; i++) {``      ``for` `(``int` `j = 0; j < N; j++)``        ``Console.Write(arr[i, j] + ``" "``);``      ``Console.WriteLine();``    ``}``  ``}` `  ``// Function to shuffle matrix``  ``public` `static` `void` `reverseAlternate(``int``[, ] arr, ``int` `K)``  ``{``    ``int` `turn = 0;``    ``int` `row = 0, col = 0;``    ``while` `(turn < K) {` `      ``// Reverse the row``      ``if` `(turn % 2 == 0) {``        ``int` `start = 0, end = N - 1, temp;``        ``while` `(start < end) {``          ``temp = arr[row % M, start];``          ``arr[row % M, start] = arr[row % M, end];``          ``arr[row % M, end] = temp;``          ``start += 1;``          ``end -= 1;``        ``}``        ``row++;``        ``turn++;``      ``}` `      ``// Reverse the column``      ``else` `{``        ``int` `start = 0, end = M - 1, temp;``        ``while` `(start < end) {``          ``temp = arr[start, col % N];``          ``arr[start, col % N] = arr[end, col % N];``          ``arr[end, col % N] = temp;``          ``start += 1;``          ``end -= 1;``        ``}``        ``col++;``        ``turn++;``      ``}``    ``}``  ``}` `  ``// Driver code``  ``public` `static` `void` `Main(``string``[] args)``  ``{` `    ``int``[, ] matrix = { { 11, 23, 43, 21 },``                      ``{ 12, 17, 65, 91 },``                      ``{ 71, 56, 34, 24 } };``    ``int` `K = 8;``    ``reverseAlternate(matrix, K);``    ``showArray(matrix);``  ``}``}` `// This code is contributed by ukasp.`

## Javascript

 ``

Output

```11 43 56 21
91 65 17 12
24 34 23 71 ```

Time Complexity: O(K * max(M, N))
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up