The question is as follows: Rotate an NxN matrix clockwise by one element and display the new matrix. For example, if
A = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10,11,12],
[13,14,15,16]]
Then the rotated matrix obtained from A will be
[[5, 1, 2, 3],
[9, 10, 6, 4],
[13, 11, 7, 8],
[14, 15, 16, 12]]
You may think of it as rotating each of the "rings" clockwise by one element. So, that was the question given to us and we were told to absolutely not use Numpy or any other library that can handle matrices.
Here's what I did:
def get_previous_pos(i, j, matrix_size):
ring_no = min(j, matrix_size-1-j, i, matrix_size-1-i)
max_no = matrix_size - 1 - ring_no
x = i + (j==ring_no) - (j==max_no) - (i==max_no and j==ring_no) + (j==max_no and i==ring_no)
y = j + (i==max_no) - (i==ring_no) - (i==max_no and j==max_no) + (i==ring_no and j==ring_no)
return x,y
def get_rotated_matrix(matrix):
n = len(matrix)
rotated_matrix = [matrix[row_no][:] for row_no in range(n)]
for i in range(n):
for j in range(n):
prev = get_previous_pos(i, j, n)
rotated_matrix[i][j] = matrix[prev[0]][prev[1]]
return rotated_matrix
n = int(input("Enter size of the square matrix: "))
matrix = [[int(input()) for j in range(n)] for i in range(n)]
print("original matrix --> ", matrix)
print("rotated matrix --> ", get_rotated_matrix(matrix))
The function, get_rotated_matrix(matrix)
takes any 2D NxN list and returns the rotated 2D list. The get_previous_pos(i,j,matrix_size)
function takes a matrix position as its (i,j) value, the matrix size(N), and returns the position of the element that will occupy (i,j) after the clockwise rotation.
I have tested this code for matrix sizes ranging from 1X1 up to 5x5. It did produce the desired output. So, I suppose its safe to say that it works. However, I'm sure there's a much better way to go about this and was wondering if you can help me out.
Edit:
I've added a bit of driver code to the original so it can be tested without further modification. I've also attached a sample input/output below for a 4x4 matrix:
Enter size of the square matrix: 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
original matrix --> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
rotated matrix --> [[5, 1, 2, 3], [9, 10, 6, 4], [13, 11, 7, 8], [14, 15, 16, 12]]