Modify a matrix by rotating ith row exactly i times in clockwise direction | java program for the above approach ; Function to reverse arr [ ] from start to end ; Function to rotate every i - th row of the matrix i times ; Traverse the matrix row - wise ; Reverse the current row ; Reverse the first i elements ; Reverse the last ( N - i ) elements ; Increment count ; Print final matrix ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void reverse ( int arr [ ] , int start , int end ) { while ( start < end ) { int temp = arr [ start ] ; arr [ start ] = arr [ end ] ; arr [ end ] = temp ; start ++ ; end -- ; } } static void rotateMatrix ( int mat [ ] [ ] ) { int i = 0 ; for ( int rows [ ] : mat ) { reverse ( rows , 0 , rows . length - 1 ) ; reverse ( rows , 0 , i - 1 ) ; reverse ( rows , i , rows . length - 1 ) ; i ++ ; } for ( int rows [ ] : mat ) { for ( int cols : rows ) { System . out . print ( cols + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; rotateMatrix ( mat ) ; } }