Skip to content
Related Articles

Related Articles

Javascript Program to Modify a matrix by rotating ith row exactly i times in clockwise direction

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 30 May, 2022

Given a matrix mat[][] of dimensions M * N, the task is to print the matrix obtained after rotating every ith row of the matrix i times in a clockwise direction.

Examples:

Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Output:
1 2 3
6 4 5
8 9 7
Explanation:
The 0th row is rotated 0 times. Therefore, the 0th row remains the same as {1, 2, 3}.
The 1st row is rotated 1 times. Therefore, the 1st row modifies to {6, 4, 5}.
The 2nd row is rotated 2 times. Therefore, the 2nd row modifies to {8, 9, 7}.
After completing the above operations, the given matrix modifies to {{1, 2, 3}, {6, 4, 5}, {8, 9, 7}}.

Input: mat[][] = {{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 8}, {7, 8, 9, 8}}
Output:
1 2 3 4
7 4 5 6
9 8 7 8
8 9 8 7

Approach: Follow the steps below to solve the problem:

Below is the implementation of the above approach:

Javascript




<script>
// javascript program for the above approach
 
// Function to reverse arr[] from start to end
function  reverse(arr,start,end)
{
    while (start < end) {
      let temp = arr[start];
      arr[start] = arr[end];
      arr[end] = temp;
      start++;
      end--;
    }
}
 
 // Function to rotate every i-th
  // row of the matrix i times
function rotateMatrix(mat)
{
    let i = 0;
  
    // Traverse the matrix row-wise
    for (let rows=0;rows<mat.length;rows++) {
  
      // Reverse the current row
      reverse(mat[rows], 0, mat[rows].length - 1);
  
      // Reverse the first i elements
      reverse(mat[rows], 0, i - 1);
  
      // Reverse the last (N - i) elements
      reverse(mat[rows], i, mat[rows].length - 1);
  
      // Increment count
      i++;
    }
  
    // Print final matrix
    for (let rows=0;rows< mat.length;rows++) {
      for (let cols=0;cols< mat[rows].length;cols++) {
        document.write(mat[rows][cols] + " ");
      }
      document.write("<br>");
    }
}
 
// Driver Code
let mat=[[ 1, 2, 3 ],
                   [ 4, 5, 6 ],
                   [ 7, 8, 9 ]];
rotateMatrix(mat);
 
 
// This code is contributed by avanitrachhadiya2155
</script>

Output: 

1 2 3 
6 4 5 
8 9 7

 

Time Complexity: O(N*M), as we are using nested loops to traverse N*M times.

Auxiliary Space: O(1), as we are not using any extra space.

Please refer complete article on Modify a matrix by rotating ith row exactly i times in clockwise direction for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!