
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rotate Image in Python
Suppose we have one 2D matrix, that is representing one image. We have to rotate this image to 90 degrees clockwise. So if the image is like
1 | 5 | 7 |
9 | 6 | 3 |
2 | 1 | 3 |
Then the output will be
2 | 9 | 1 |
1 | 6 | 5 |
3 | 3 | 7 |
To solve this, we will follow these steps −
- Consider temp_mat = [], col := length of matrix – 1
- for col in range 0 to length of matrix
- temp := []
- for row in range length of matrix – 1 down to -1
- add matrix[row, col] in temp
- add temp into temp_mat
- for i in range 0 to length of matrix
- for j in range 0 to length of matrix
- matrix[i, j] := temp_mat[i, j]
- for j in range 0 to length of matrix
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def rotate(self, matrix): temp_matrix = [] column = len(matrix)-1 for column in range(len(matrix)): temp = [] for row in range(len(matrix)-1,-1,-1): temp.append(matrix[row][column]) temp_matrix.append(temp) for i in range(len(matrix)): for j in range(len(matrix)): matrix[i][j] = temp_matrix[i][j] return matrix ob1 = Solution() print(ob1.rotate([[1,5,7],[9,6,3],[2,1,3]]))
Input
[[1,5,7],[9,6,3],[2,1,3]]
Output
[[2,9,1],[1,6,5],[3,3,7]]
Advertisements