在 Python 中旋转矩阵
pythonserver side programmingprogramming
假设我们有一个 n x n 二维矩阵。我们必须将该矩阵顺时针旋转 90 度。因此,如果矩阵是这样的-
1 | 5 | 7 |
9 | 6 | 3 |
2 | 1 | 3 |
然后输出将是
2 | 9 | 1 |
1 | 6 | 5 |
3 | 3 | 7 |
要解决为此,我们将遵循以下步骤 −
- 考虑 temp_mat = [], col := 矩阵长度 – 1
- 对于 col,范围从 0 到矩阵长度
- temp := []
- 对于 row,范围从矩阵长度 – 1 到 -1
- 在 temp 中添加 matrix[row, col]
- 将 temp 添加到 temp_mat
- 对于 i,范围从 0 到矩阵长度
- 对于 j,范围从 0 到矩阵长度
- matrix[i, j] := temp_mat[i, j]
- 对于 j,范围从 0 到矩阵长度
让我们看看下面的实现以便更好地理解 −
Example Code (Python)
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]]))
输入
[[1,5,7],[9,6,3],[2,1,3]]
输出
[[2, 9, 1], [1, 6, 5], [3, 3, 7]]