0

# Wat was the error in the program to find rotating the matrix counter clockwise by 90 degree

2 Answers

+ 1

N=4
def rotateMatrix(mat):
for x in range(0, int(N / 2)):
for y in range(x, N-x-1):
temp = mat[x][y]
mat[x][y] = mat[y][N-1-x]
mat[y][N-1-x] = mat[N-1-x][N-1-y]
mat[N-1-x][N-1-y] = mat[N-1-y][x]
mat[N-1-y][x] = temp
def displayMatrix( mat ):
for i in range(0, N):
for j in range(0, N):
print (mat[i][j], end = ' ')
print ("")
mat = [[0 for x in range(N)] for y in range(N)]
mat = [ [1, 2, 3, 4 ],[5, 6, 7, 8 ],[9, 10, 11, 12 ],[13, 14, 15, 16 ] ]
rotateMatrix(mat)
# Print rotated matrix
displayMatrix(mat)
#In python white spaces are matters, counted as indentations..

+ 2

Works fine after removing invalid characters
def rotateMatrix(mat):
for x in range(0, int(N / 2)):
for y in range(x, N-x-1):
temp = mat[x][y]
mat[x][y] = mat[y][N-1-x]
mat[y][N-1-x] = mat[N-1-x][N-1-y]
mat[N-1-x][N-1-y] = mat[N-1-y][x]
mat[N-1-y][x] = temp
def displayMatrix( mat ):
for i in range(0, N):
for j in range(0, N):
print (mat[i][j], end = ' ')
print ("")
mat = [[0 for x in range(N)] for y in range(N)]
mat = [ [1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12 ],
[13, 14, 15, 16 ]]
'''
# Test case 2
mat = [ [1, 2, 3 ],
[4, 5, 6 ],
[7, 8, 9 ] ]
# Test case 3
mat = [ [1, 2 ],
[4, 5 ] ]
'''
rotateMatrix(mat)
# Print rotated matrix
displayMatrix(mat)
When you copy paste some formatted text from other resources you usually end up with those invalid characters which you have to delete