Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction | Function to prlet the matrix ; Iterate over the rows ; Iterate over the columns ; Print the value ; Function to perform the swapping of matrix elements in clockwise manner ; Stores the last row ; Stores the last column ; Perform the swaps ; Function to rotate non - diagonal elements of the matrix K times in clockwise direction ; Update K to K % 4 ; Iterate until K is positive ; Iterate each up to N / 2 - th row ; Iterate each column from i to N - i - 1 ; Check if the element at i , j is not a diagonal element ; Perform the swapping ; Print the matrix ; Driver Code
function print ( mat ) { for ( let i = 0 ; i < mat . length ; i ++ ) { for ( let j = 0 ; j < mat [ 0 ] . length ; j ++ ) document . write ( mat [ i ] [ j ] + " " ) ; document . write ( " " ) ; } } function performSwap ( mat , i , j ) { let N = mat . length ; let ei = N - 1 - i ; let ej = N - 1 - j ; let temp = mat [ i ] [ j ] ; mat [ i ] [ j ] = mat [ ej ] [ i ] ; mat [ ej ] [ i ] = mat [ ei ] [ ej ] ; mat [ ei ] [ ej ] = mat [ j ] [ ei ] ; mat [ j ] [ ei ] = temp ; } function rotate ( mat , N , K ) { K = K % 4 ; while ( K -- > 0 ) { for ( let i = 0 ; i < N / 2 ; i ++ ) { for ( let j = i ; j < N - i - 1 ; j ++ ) { if ( i != j && ( i + j ) != N - 1 ) { performSwap ( mat , i , j ) ; } } } } print ( mat ) ; } let K = 5 ; let mat = [ [ 1 , 2 , 3 , 4 ] , [ 6 , 7 , 8 , 9 ] , [ 11 , 12 , 13 , 14 ] , [ 16 , 17 , 18 , 19 ] , ] ; let N = mat . length ; rotate ( mat , N , K ) ;