Saturday, June 25, 2022
HomeTechnologyFlip the given Matrix along both diagonals in clockwise direction

# Flip the given Matrix along both diagonals in clockwise direction

Given a matrix arr[][] of size M*N, where M is the number of rows and N is the number of columns. The task is to flip the matrix by both diagonals. Flipping the matrix means rotating all elements of the matrix in a clockwise direction, along the diagonal
Examples:

Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }
Output: { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }
Explanation: Resultant matrix after flipping the matrix along the main diagonal: { {1, 4, 7}, {2, 5, 8}, {3, 6, 9} }
Resultant matrix after flipping the matrix along the second diagonal: { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[][] = { {1,  2,  3,  4}, {5,  6,  7,  8}, {9,  10, 11, 12}, {13, 14, 15, 16} }
Output: { {16, 15, 14, 13}, {12, 11, 10, 9}, {8, 7, 6, 5}, {4, 3, 2, 1} }

Approach: The task can easily be solved using observations. One can observe that the resultant matrix would contain reversed rows in reverse order. Follow the below steps to solve the problem:

• Iterate over the rows of the matrix, and swap elements of the first row & last row in reverse order, and similarly second row & second last row, and so on.

Below is the implementation of the above code:

## C++

 `#include ` `using` `namespace` `std;`   `const` `int` `m = 4, n = 4;`   `void` `flip(``int` `matrix[m][n])` `{` `    ``int` `i, j, temp;` `      `  `      ` `    ``for` `(i = 0; i < m / 2; i++) {` `        ``for` `(j = 0; j < n; j++) {` `            ``temp = matrix[i][j];` `            ``matrix[i][j] = matrix[m - 1 - i][n - 1 - j];` `            ``matrix[m - 1 - i][n - 1 - j] = temp;` `        ``}` `    ``}` `}`   `void` `show(``int` `matrix[m][n])` `{` `    ``int` `i, j;` `    ``for` `(i = 0; i < m; i++) {` `        ``for` `(j = 0; j < n; j++) {` `            ``cout << matrix[i][j] << ``"  "``;` `        ``}` `        ``cout << endl;` `    ``}` `}`   `int` `main()` `{`   `    ``int` `matrix[4][4] = { { 1, 2, 3, 4 },` `                         ``{ 5, 6, 7, 8 },` `                         ``{ 9, 10, 11, 12 },` `                         ``{ 13, 14, 15, 16 } };`   `    ``flip(matrix);` `    ``show(matrix);` `}`

## Javascript

 ``

Output

```16  15  14  13
12  11  10  9
8  7  6  5
4  3  2  1  ```

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

RELATED ARTICLES