VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-the-rows-and-columns-of-a-matrix-alternatively/

⇱ Reverse the rows and columns of a matrix alternatively - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse the rows and columns of a matrix alternatively

Last Updated : 31 Dec, 2021

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 reverse the rows and columns of the matrix alternatively i.e start with reversing the 1st row, then the 2nd column, and so on.

Examples

Input: arr[][] = { 
{3,      4,   1,    8},  
{11, 23, 43, 21},  
{12, 17, 65, 91},  
{71, 56, 34, 24} 
}
Output: { 
{8,    56,   4, 24},  
{11, 17, 43, 12},  
{91, 65, 23, 21},  
{71,   1, 34,  3} 
}
Explanation: Operations to be followed: 

  • Reverse the first row
  • Reverse the second column
  • Reverse the third row
  • Reverse the fourth row

Input: { {11, 23, 43, 21}, {12, 17, 65, 91}, {71, 56, 34, 24} }
Output: { {21, 56, 23, 71}, {12, 17, 65, 91}, {24, 34, 43, 11} } 

Approach: The task can be solved by simply running two while loops for traversing rows and columns alternatively. In the end, print the resultant matrix.

Below is the implementation of the above approach:


Output
8 56 4 24 
11 17 43 12 
91 65 23 21 
71 1 34 3 

Time Complexity: O(M*N)
Space Complexity: O(1), no additional extra space is used.


 

Comment