Open In App

Rotate Matrix Counterclockwise by 1

Last Updated : 18 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Examples:

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

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

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 back (except the first element)
b) Move the rightmost column elements one position up (except the first element)
c) Move the bottom row elements one position right (Except the rightmost element)
d) Move the first column elements one position down (Except the bottom elements)

2. Repeat the same process for inner layers.

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

// Function to rotate a matrix counterclockwise
void rotateMatrix(vector<vector<int>>& 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 column
        prev = mat[row][col + 1];

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

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

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

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

int main() {
    vector<vector<int>> 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
import java.util.Arrays;

class GfG {
  
    // Function to rotate a matrix counterclockwise
     static void rotateMatrix(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;

        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 column
            prev = mat[row][col + 1];

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

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

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

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

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

        rotateMatrix(mat);

        // Print the rotated matrix
        for (int[] r : mat) {
            for (int val : r)
                System.out.print(val + " ");
            System.out.println();
        }
    }
}
Python
def rotateMatrix(mat):
  
    # Function to rotate a matrix counterclockwise
    m = len(mat)
    n = len(mat[0])
    
    row = 0
    col = 0
    prev = 0
    curr = 0

    # Rotate the matrix in layers
    while row < m and col < n:
        if row + 1 == m or col + 1 == n:
            break

        # Store the first element of the next column
        prev = mat[row][col + 1]

        # Move elements of the first column
        for i in range(row, m):
            curr = mat[i][col]
            mat[i][col] = prev
            prev = curr
        col += 1

        # Move elements of the last row
        for i in range(col, n):
            curr = mat[m - 1][i]
            mat[m - 1][i] = prev
            prev = curr
        m -= 1

        # Move elements of the last column
        if col < n:
            for i in range(m - 1, row - 1, -1):
                curr = mat[i][n - 1]
                mat[i][n - 1] = prev
                prev = curr
        n -= 1

        # Move elements of the first row
        if row < m:
            for i in range(n - 1, col - 1, -1):
                curr = mat[row][i]
                mat[row][i] = prev
                prev = curr
        row += 1

if __name__ == "__main__":
    mat = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]
    ]

    rotateMatrix(mat)

    for r in mat:
        print(" ".join(map(str, r)))
C#
using System;

class GfG {
  
    // Function to rotate a matrix counterclockwise
     static void rotateMatrix(int[][] mat) {
        int m = mat.Length;
        int n = mat[0].Length;

        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 column
            prev = mat[row][col + 1];

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

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

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

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

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

        rotateMatrix(mat);

        // Print the rotated matrix
        foreach (var r in mat) {
            foreach (int val in r)
                Console.Write(val + " ");
            Console.WriteLine();
        }
    }
}
JavaScript
function rotateMatrix(mat) {

    // Function to rotate a matrix counterclockwise
    let m = mat.length;
    let n = mat[0].length;

    let row = 0, col = 0;
    let 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 column
        prev = mat[row][col + 1];

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

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

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

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

const mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
];
rotateMatrix(mat);
mat.forEach(r => {
    console.log(r.join(" "));
});

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

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


Next Article
Article Tags :
Practice Tags :

Similar Reads