如何在不使用任何额外空间的情况下将矩阵旋转 90 度? [英] How to rotate a matrix 90 degrees without using any extra space?

查看:21
本文介绍了如何在不使用任何额外空间的情况下将矩阵旋转 90 度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
将图像旋转 90 度的算法地方?(没有额外的内存)

说 90 度我的意思是说:

By saying 90 degrees i mean to say if:

A = {1,2,3,
     4,5,6,
     7,8,9}

然后旋转 90 度后 A 变为:

then after 90 degree rotation A becomes:

A = {7,4,1,
     8,5,2,
     9,6,3}

推荐答案

a 成为一个基于 nxn 数组 0 的索引

let a be an nxn array 0 based indexing

f = floor(n/2)
c = ceil(n/2)

for x = 0 to f - 1
  for y = 0 to c - 1
    temp = a[x,y]
    a[x,y] = a[y,n-1-x]
    a[y,n-1-x] = a[n-1-x,n-1-y]
    a[n-1-x,n-1-y] = a[n-1-y,x]
    a[n-1-y,x] = temp

编辑如果你想避免使用临时文件,这一次在 python 中有效(它也以正确的方向旋转).

Edit If you want to avoid using temp, this works (it also rotates in the correct direction) this time in python.

def rot2(a):
  n = len(a)
  c = (n+1) / 2
  f = n / 2
  for x in range(c):
    for y in range(f):
      a[x][y] = a[x][y] ^ a[n-1-y][x]
      a[n-1-y][x] = a[x][y] ^ a[n-1-y][x]
      a[x][y] = a[x][y] ^ a[n-1-y][x]

      a[n-1-y][x] = a[n-1-y][x] ^ a[n-1-x][n-1-y]
      a[n-1-x][n-1-y] = a[n-1-y][x] ^ a[n-1-x][n-1-y]
      a[n-1-y][x] = a[n-1-y][x] ^ a[n-1-x][n-1-y]

      a[n-1-x][n-1-y] = a[n-1-x][n-1-y]^a[y][n-1-x]
      a[y][n-1-x] = a[n-1-x][n-1-y]^a[y][n-1-x]
      a[n-1-x][n-1-y] = a[n-1-x][n-1-y]^a[y][n-1-x]

注意:这只适用于整数矩阵.

Note: This only works for matrices of integers.

这篇关于如何在不使用任何额外空间的情况下将矩阵旋转 90 度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆