如何旋转二维数组? [英] How do you rotate a two dimensional array?

查看:47
本文介绍了如何旋转二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

受到 Raymond Chen 的帖子的启发,假设您有一个 4x4二维数组,编写一个将其旋转 90 度的函数.Raymond 在伪代码中链接到了一个解决方案,但我想看看一些现实世界的东西.

Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.

[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]

变成:

[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]

更新:Nick 的回答是最直接的,但是有没有比 n^2 更好的方法呢?如果矩阵是 10000x10000 会怎样?

Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?

推荐答案

O(n^2) 时间和 O(1) 空间算法(没有任何变通方法和笨拙的东西!)

O(n^2) time and O(1) space algorithm ( without any workarounds and hanky-panky stuff! )

旋转 +90:

  1. 转置
  2. 反转每一行

旋转 -90:

方法一:

  1. 转置
  2. 反转每一列

方法二:

  1. 反转每一行
  2. 转置

旋转 +180 度:

方法一:旋转+90两次

方法二:每行反转再反转每列(转置)

Method 2: Reverse each row and then reverse each column (Transpose)

旋转 -180 度:

方法一:旋转-90度两次

方法二:先反转每一列再反转每一行

Method 2: Reverse each column and then reverse each row

方法 3:旋转 +180,因为它们相同

Method 3: Rotate by +180 as they are same

这篇关于如何旋转二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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