Open In App

Javascript Program to Rotate Matrix Elements

Last Updated : 23 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a matrix, clockwise rotate elements in it.

Examples:

Input:
1    2    3
4    5    6
7    8    9

Output:
4    1    2
7    5    3
8    9    6

For 4*4 matrix
Input:
1    2    3    4    
5    6    7    8
9    10   11   12
13   14   15   16

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

The idea is to use loops similar to the program for printing a matrix in spiral form. One by one rotate all rings of elements, starting from the outermost. To rotate a ring, we need to do following. 

  1. Move elements of top row. 
  2. Move elements of last column. 
  3. Move elements of bottom row. 
  4. Move elements of first column. 

Repeat above steps for inner ring while there is an inner ring.

Below is the implementation of above idea.

JavaScript
// Javascript program to rotate a matrix    

let R = 4;
let C = 4;

// A function to rotate a matrix 
// mat[][] of size R x C.
// Initially, m = R and n = C
function rotatematrix(m, n, mat) {
    let row = 0, col = 0;
    let prev, curr;

    /*
    row - Starting row index
    m - ending row index
    col - starting column index
    n - ending column index
    i - iterator
    */
    while (row < m && col < n) {
        if (row + 1 == m || col + 1 == n)
            break;

        // Store the first element of next
        // row, this element will replace 
        // first element of current row
        prev = mat[row + 1][col];

        // Move elements of first row 
        // from the remaining rows 
        for (let i = col; i < n; i++) {
            curr = mat[row][i];
            mat[row][i] = prev;
            prev = curr;
        }
        row++;

        // Move elements of last column
        // from the remaining columns 
        for (let i = row; i < m; i++) {
            curr = mat[i][n - 1];
            mat[i][n - 1] = prev;
            prev = curr;
        }
        n--;

        // Move elements of last row 
        // from the remaining rows 
        if (row < m) {
            for (let i = n - 1; i >= col; i--) {
                curr = mat[m - 1][i];
                mat[m - 1][i] = prev;
                prev = curr;
            }
        }
        m--;

        // Move elements of first column
        // from the remaining rows 
        if (col < n) {
            for (let i = m - 1; i >= row; i--) {
                curr = mat[i][col];
                mat[i][col] = prev;
                prev = curr;
            }
        }
        col++;
    }

    // Print rotated matrix
    for (let i = 0; i < R; i++) {
        let output = "";
        for (let j = 0; j < C; j++)
            output += mat[i][j] + " "
        console.log(output);
    }
}

// Driver code

let a = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]];

rotatematrix(R, C, a);

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

Complexity Analysis:

  • Time Complexity: O(max(m,n) * max(m,n))
  • Auxiliary Space: O(m*n)

Using Transpose and Reverse

This approach first transposes the matrix and then reverses each row to achieve the clockwise rotation.

  • Step 1: Transpose the Matrix: Swap matrix[i][j] with matrix[j][i].
  • Step 2: Reverse Each Row: Reverse each row of the transposed matrix.

Example: In this example The rotateMatrix function rotates a matrix clockwise by first transposing it (swapping rows and columns) and then reversing each row. It correctly rotates the given matrices in both test cases.

JavaScript
// Function to rotate a matrix clockwise
function rotateMatrix(matrix) {
    const n = matrix.length;

    // Transpose the matrix
    for (let i = 0; i < n; i++) {
        for (let j = i; j < n; j++) {
            // Swap matrix[i][j] with matrix[j][i]
            [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
        }
    }

    // Reverse each row
    for (let i = 0; i < n; i++) {
        matrix[i].reverse();
    }

    return matrix;
}

// Test Case 1
let matrix1 = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
];

console.log("Original Matrix:");
console.log(matrix1);
console.log("Rotated Matrix:");
console.log(rotateMatrix(matrix1));

// Test Case 2
let matrix2 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

console.log("Original Matrix:");
console.log(matrix2);
console.log("Rotated Matrix:");
console.log(rotateMatrix(matrix2));

Output
Original Matrix:
[
  [ 1, 2, 3, 4 ],
  [ 5, 6, 7, 8 ],
  [ 9, 10, 11, 12 ],
  [ 13, 14, 15, 16 ]
]
Rotated Matrix:
[
  [ 13, 9, 5, 1 ],
  [ 14, 10, 6, 2 ],
  [ 15, 11, 7, 3 ],
  [ 16, 12, 8, 4 ]
]
Original Matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Rotated Matrix:
[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]

Complexity Analysis:

  • Time Complexity: O(N2)
  • Space Complexity: O(1)

Please refer complete article on Rotate Matrix Elements for more details!



Next Article
Practice Tags :

Similar Reads