A square n×n matrix of integers can be written in Python as a list with n elements, where each element is in turn a list of n integers, representing a row of the matrix. For instance, the matrix
1 2 3
4 5 6
7 8 9
would be represented as [[1,2,3], [4,5,6], [7,8,9]].
Write a function rotate(m) that takes a list representation m of a square matrix as input, and returns the matrix obtained by rotating the original matrix clock-wise by 90 degrees. For instance, if we rotate the matrix above, we get
7 4 1
8 5 2
9 6 3
Your function should not modify the argument m provided to the function rotate().
Answers
Answer:
# Program to rotate a matrix
def rotate(m):
# Initializing an empty nxn matrix, similar to the input dimension of m
new_m = [[0 for a in range(len(m[0]))] for i in range(len(m))]
# Transpose action of the matrix done below
for i in range(len(m)):
for j in range(len(m[i])):
new_m[j][i]=m[i][j]
for x in range(len(new_m)):
new_m[x].reverse()
# Printing the original matrix
print(m)
# Printing the output reversed matrix
print(new_m)
NOTE: anything written after "#" is a comment in python.
N=6
def rotate(matrix):
for x in range(0, int(N/2)):
for y in range(x, N-x-1):
t = mat[x][y]
matrix[x][y] = matrix[y][N-1-x]
matrix[y][N-1-x] = matrix[N-1-x][N-1-y]
matrix[N-1-x][N-1-y] = matrix[N-1-y][x]
matrix[N-1-y][x] = t
The logic here is to store the current cell value in the variable ‘t’, move the values from right to top, then move values from bottom to right and move numbers from left to bottom, then finally assign the value of ‘t’ to the given position in the last line of the function.