POTD #1 Rotate by 90 degree - Matrix Anticlockwise | Geeks For Geeks
After a long time, i tried competitive programming. Seems i need to do it more. This is a geeks for geeks POTD (Problem of the day) problem.
Link: https://www.geeksforgeeks.org/problems/rotate-by-90-degree-1587115621/1
Given a square matrix mat[][] of size n x n. The task is to rotate it by 90 degrees in an anti-clockwise direction without using any extra space.
Input:
Input: mat[][] = [[1, 2, 3],
[4, 5, 6]
[7, 8, 9]]
Output: Rotated Matrix:
[3, 6, 9]
[2, 5, 8]
[1, 4, 7]
Input: mat[][] = [[1, 2], [3, 4]] Output: Rotated Matrix: [2, 4] [1, 3]
Solution
I tried to reverse the each row and found the transpose of the matrix. Since i am aware of transpose , i directly went to this approach.
#User function Template for python3
class Solution:
#Function to rotate matrix anticlockwise by 90 degrees.
def rotateby90(self, mat):
# code here
n = len(mat)
# reversing
for row in mat:
i = 0
j = len(row) - 1
while i < j:
row[i], row[j] = row[j], row[i]
i += 1
j -= 1
# Performing Transpose
for i in range(n):
for j in range(i + 1, n):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]

Originally published on parottasalna.com.