How do you rotate a two dimensional array?

后端 未结 30 3120
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

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

30条回答
  •  醉酒成梦
    2020-11-22 03:34

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

    Rotate by +90:

    1. Transpose
    2. Reverse each row

    Rotate by -90:

    Method 1 :

    1. Transpose
    2. Reverse each column

    Method 2 :

    1. Reverse each row
    2. Transpose

    Rotate by +180:

    Method 1: Rotate by +90 twice

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

    Rotate by -180:

    Method 1: Rotate by -90 twice

    Method 2: Reverse each column and then reverse each row

    Method 3: Rotate by +180 as they are same

提交回复
热议问题