定义一个矩阵类,其中包含了矩阵的维数,矩阵,以及需要的方法 输入一个m*n的矩阵,将这个矩阵向右旋转90度后输出 比如现在有2*3矩阵 :
时间: 2024-02-12 14:48:03 浏览: 75
输入矩阵阶数n,给n阶矩阵的元素按行序由1到n*n顺序赋值,然后将其向右旋转90度,输出旋转后的矩阵。
class Matrix:
def __init__(self, m, n):
self.m = m
self.n = n
self.matrix = [[0 for i in range(n)] for j in range(m)]
def rotate(self):
new_matrix = [[0 for i in range(self.m)] for j in range(self.n)]
for i in range(self.m):
for j in range(self.n):
new_matrix[j][self.m - 1 - i] = self.matrix[i][j]
self.matrix = new_matrix
self.m, self.n = self.n, self.m
def print_matrix(self):
for i in range(self.m):
for j in range(self.n):
print(self.matrix[i][j], end=' ')
print()
# Example usage:
m = 2
n = 3
data = [[1, 2, 3], [4, 5, 6]]
matrix = Matrix(m, n)
matrix.matrix = data
matrix.rotate()
matrix.print_matrix() # Output: 4 1 \n 5 2 \n 6 3
阅读全文