You can learn more about what to expect in these emails here.
Table of Contents
Problem
You are given a 2D matrix of dimension and a positive integer . You have to rotate the matrix times and print the resultant matrix. Rotation should be in anti-clockwise direction.
Rotation of a matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only.
I’m providing the solution for Python and JS, please leave on the comments if you found a better way.
I really got the solution inspired by the image on the problem statement above. The idea is to resolve one “layer” at a time.
For each layer I’m building a flat array with the elements assigned to the correct position as it’s easier to do this on 1 dimension. After I complete the array, I then proceed to recreate the matrix layer from it.
The problem was actually quite simple to solve, though it looks messy.
I like using variables to define the direction where I’m going while looping through the matrix layer, though some solutions for problems like this usually don’t use this directional variables, but multiple loops instead. anyway works.
Here is my solution as always for Python and JS
defrotateRing(matrix, r, offset):
col_len = len(matrix[0]) - (offset*2)
row_len = len(matrix) - (offset*2)
if col_len ==0or row_len ==0:
return flat = [None] * (col_len *2+ (row_len-2) *2)
x_dir =1 y_dir =0 col = offset
row = offset
for i in range(len(flat)):
final_pos = i - (r % len(flat))
flat[final_pos] = matrix[row][col]
col += x_dir
row += y_dir
if x_dir >0and col == col_len -1+ offset:
x_dir =0 y_dir =1elif x_dir <0and col == offset:
x_dir =0 y_dir =-1elif y_dir >0and row == row_len -1+ offset:
x_dir =-1 y_dir =0elif y_dir <0and row == offset:
x_dir =1 y_dir =0 x_dir =1 y_dir =0 col = offset
row = offset
for i in range(len(flat)):
matrix[row][col] = flat[i]
col += x_dir
row += y_dir
if x_dir >0and col == col_len -1+ offset:
x_dir =0 y_dir =1elif x_dir <0and col == offset:
x_dir =0 y_dir =-1elif y_dir >0and row == row_len -1+ offset:
x_dir =-1 y_dir =0elif y_dir <0and row == offset:
x_dir =1 y_dir =0defmatrixRotation(matrix, r):
for offset in range(math.floor(min(len(matrix), len(matrix[0]))/2)):
rotateRing(matrix, r, offset)
for row in matrix:
for col in row:
print(col, end=" ")
print("")
You can learn more about what to expect in these emails here.
Our website uses cookies to make your browsing experience better. By using our site you agree to our use of cookies. Learn more by reading our privacy policy.