Rotate Matrix Clockwise by 1 (original) (raw)

Last Updated : 17 Oct, 2024

Given a square matrix, the task is to rotate its elements clockwise by one step.

**Examples:

**Input
1 2 3
4 5 6
7 8 9
**Output:
4 1 2
7 5 3
8 9 6

**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

Try It Yourselfredirect icon

The idea is to use nested loops to move elements in four directions (right, down, left, and up) one step at a time for each layer starting from the outermost layer. This simulates the clockwise rotation by rotating each "ring" or layer of the matrix.

1. First move the elements of the outermost layer.
a) Move the top row elements one position ahead (except the last element)
b) Move the rightmost column elements one position down (except the last element)
c) Move the bottom row elements one position left (Except the leftmost element)
d) Move the first column elements one position up (Except the top elements)

2. Repeat the same process for inner layers.

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to rotate a matrix represented by a vector of vectors void rotateMatrix(vector<vector>& mat) {

int m = mat.size();
int n = mat[0].size();

int row = 0, col = 0;
int prev, curr;

// Rotate the matrix in layers
while (row < m && col < n) {
    if (row + 1 == m || col + 1 == n)
        break;

    // Store the first element of the next row
    prev = mat[row + 1][col];

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

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

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

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

}

int main() { vector<vector> mat = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} };

rotateMatrix(mat);

// Print the rotated matrix
for (auto& r : mat) {
    for (int val : r)
        cout << val << " ";
    cout << endl;
}

return 0;

}

Java

// Java program to rotate a matrix import java.lang.; import java.util.;

class GFG { static int R = 4; static int C = 4;

// A function to rotate a matrix
// mat[][] of size R x C.
// Initially, m = R and n = C
static void rotatematrix(int m, int n, int mat[][])
{
    int row = 0, col = 0;
    int 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 (int 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 (int 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 (int 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 (int i = m - 1; i >= row; i--) {
                curr = mat[i][col];
                mat[i][col] = prev;
                prev = curr;
            }
        }
        col++;
    }

    // Print rotated matrix
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++)
            System.out.print(mat[i][j] + " ");
        System.out.print("\n");
    }
}

/* Driver program to test above functions */
public static void main(String[] args)
{

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

    rotatematrix(R, C, a);
}

}

Python

Python program to rotate a matrix

Function to rotate a matrix

def rotateMatrix(mat):

if not len(mat):
    return

"""
    top : starting row index
    bottom : ending row index
    left : starting column index
    right : ending column index
"""

top = 0
bottom = len(mat)-1

left = 0
right = len(mat[0])-1

while left < right and top < bottom:

    # Store the first element of next row,
    # this element will replace first element of
    # current row
    prev = mat[top+1][left]

    # Move elements of top row one step right
    for i in range(left, right+1):
        curr = mat[top][i]
        mat[top][i] = prev
        prev = curr

    top += 1

    # Move elements of rightmost column one step downwards
    for i in range(top, bottom+1):
        curr = mat[i][right]
        mat[i][right] = prev
        prev = curr

    right -= 1

    # Move elements of bottom row one step left
    for i in range(right, left-1, -1):
        curr = mat[bottom][i]
        mat[bottom][i] = prev
        prev = curr

    bottom -= 1

    # Move elements of leftmost column one step upwards
    for i in range(bottom, top-1, -1):
        curr = mat[i][left]
        mat[i][left] = prev
        prev = curr

    left += 1

return mat

Utility Function

def printMatrix(mat): for row in mat: print row

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

matrix = rotateMatrix(matrix)

Print modified matrix

printMatrix(matrix)

C#

// C# program to rotate a matrix

using System;

class GFG {

static int R = 4;
static int C = 4;

// A function to rotate a matrix
// mat[][] of size R x C.
// Initially, m = R and n = C
static void rotatematrix(int m, int n, int[, ] mat)
{
    int row = 0, col = 0;
    int 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 (int 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 (int 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 (int 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 (int i = m - 1; i >= row; i--) {
                curr = mat[i, col];
                mat[i, col] = prev;
                prev = curr;
            }
        }
        col++;
    }

    // Print rotated matrix
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++)
            Console.Write(mat[i, j] + " ");
        Console.Write("\n");
    }
}

  static void Main() {
    int[, ] a = { { 1, 2, 3, 4 },
                  { 5, 6, 7, 8 },
                  { 9, 10, 11, 12 },
                  { 13, 14, 15, 16 } };

    rotatematrix(R, C, a);
}

}

JavaScript

// Function to rotate the matrix in a clockwise direction function rotateMatrix(matrix) { let m = matrix.length; let n = matrix[0].length; let row = 0, col = 0; let prev, curr;

/*
row - Starting row index
m - ending row index
col - starting column index
n - ending column index
*/

while (row < m && col < n) {

    if (row + 1 === m || col + 1 === n)
        break;

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

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

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

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

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

}

// Function to print the matrix function printMatrix(matrix) { for (let i = 0; i < matrix.length; i++) { console.log(matrix[i].join(' ')); } }

// Main function to test the rotation function main() { let matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ];

rotateMatrix(matrix);
printMatrix(matrix);

}

// Run the main function main();

`

Output

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

**Time Complexity: O(m*n) where m is the number of rows & n is the number of columns.
**Auxiliary Space: O(1).