输入是一个N x N矩阵,必须循环移位(顺时针或逆时针)一个元素。
示例输入(尺寸3):
1 2 3
4 5 6
7 8 9
输出
2 3 6
1 5 9
4 7 8
示例输入(尺寸4):
10 20 5 5
22 33 4 10
2 6 8 9
55 11 66 7
输出
22 10 20 5
2 6 33 5
55 8 4 10
11 66 7 9
我需要知道如何解决这个问题。
答案 0 :(得分:0)
要进行轮换,请按顺序阅读元素:
我 - > 0到n-1和j = 0
j - > 0到n-1,i = n-1
我 - > n-1到0和j = n-1
j - > n-1到0且i = 0
import collections
def shiftMatrix(matrix, layers, num,rotate_direction):
for count in range(layers):
temp1 = []
i = count
for j in range(count, num - count):
temp1.append(matrix[i][j])
j = num - 1 - count
for i in range(1 + count, num - count -1):
temp1.append(matrix[i][j])
i = num - 1 - count
for j in range(num - 1 - count, -1 + count, -1):
temp1.append(matrix[i][j])
j = count
for i in range(num - 1 - count - 1, 0 + count, -1):
temp1.append(matrix[i][j])
temp = collections.deque(temp1)
temp.rotate(rotate_direction)
temp1 = list(temp)
counter = 0
i = count
for j in range(count, num - count):
matrix[i][j] = temp1[counter]
counter += 1
j = num - 1 - count
for i in range(1 + count, num - count -1):
matrix[i][j] = temp1[counter]
counter += 1
i = num - 1 - count
for j in range(num - 1 - count, -1 + count, -1):
matrix[i][j] = temp1[counter]
counter += 1
j = count
for i in range(num - 1 - count - 1, 0 + count, -1):
matrix[i][j] = temp1[counter]
counter += 1
return matrix
if __name__ == '__main__':
num = int(raw_input())
op_type = raw_input()
matrix = []
for i in range(num):
temp = []
input_string = raw_input().split()
for element in input_string:
temp.append(int(element))
matrix.append(temp)
if(num >= 3):
layers = num - 3 + 1
else:
layers = 1
if(op_type == "CW"):
matrix_result = shiftMatrix(matrix,layers,num,1);
else:
matrix_result = shiftMatrix(matrix,layers,num,-1);
print(" ".join((" ".join(map(str,element))) for element in matrix_result))
说明: 尺寸N的矩阵的层数是N-3。对于每一层,元素已经以顺时针方式收集。然后转换成一个顺时针或逆时针旋转的队列。