题目地址: https://www.hackerrank.com/challenges/matrix-rotation-algo/problem?isFullScreen=false
翻译:将一个mXn的矩阵按步长r逆时针螺旋旋转。例子如下:
难度:Hard
解题
本来想找找有没有公式一步到位,然并没有找到。那只能一圈一圈拿出来了。本来想拿的时候能不能两个for嵌套完事,无奈能力有限,想了好久也没搞定。最后只能分上下左右4个循环整了。
import copy
def matrixRotation(matrix, r, m, n):
# Write your code here
layer = int(min(m,n) / 2) # 计算几个圈
temp = [[] for i in range(layer)] # 用来存圈
# 四角指针
r_top=0
r_bottom=m-1
c_left=0
c_right=n-1
while (r_top <= r_bottom and c_left <= c_right):
for i in range(c_left, c_right): # 上
temp[r_top].append(matrix[r_top][i])
for i in range(r_top, r_bottom): # 右
temp[r_top].append(matrix[i][c_right])
for i in range(c_right, c_left, -1): # 下
temp[r_top].append(matrix[r_bottom][i])
for i in range(r_bottom, r_top, -1): # 左
temp[r_top].append(matrix[i][c_left])
# 换圈
r_top += 1
r_bottom -= 1
c_left += 1
c_right -= 1
rotat_temp = copy.deepcopy(temp) # 深拷贝用来滑动
for i in range(len(temp)):
r_k = r % len(temp[i])
for j in range(len(temp[i])): # 滑起来
rotat_temp[i][j] = temp[i][(j+r_k)%len(temp[i])]
# 用来把圈还原成正常二维数组
rt = [[0 for i in range((j-1)*n+1,n*j+1)] for j in range(1,m+1)]
# 四神归位
r_top=0
r_bottom=m-1
c_left=0
c_right=n-1
# 反向操作
while (r_top <= r_bottom and c_left <= c_right):
for i in range(c_left, c_right): # top
rt[r_top][i] = str(rotat_temp[r_top].pop(0))
for i in range(r_top, r_bottom): # right
rt[i][c_right] = str(rotat_temp[r_top].pop(0))
for i in range(c_right, c_left, -1): # bottom
rt[r_bottom][i] = str(rotat_temp[r_top].pop(0))
for i in range(r_bottom, r_top, -1): # left
rt[i][c_left] = str(rotat_temp[r_top].pop(0))
r_top += 1
r_bottom -= 1
c_left += 1
c_right -= 1
# 打印收工
for i in rt:
print(' '.join(i))
这么搞居然可以通过所有case。那么问题来了,究竟能不能少点循环呢?