How do you rotate a two dimensional array?

后端 未结 30 3089
耶瑟儿~
耶瑟儿~ 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:31

    There are a lot of answers already, and I found two claiming O(1) time complexity. The real O(1) algorithm is to leave the array storage untouched, and change how you index its elements. The goal here is that it does not consume additional memory, nor does it require additional time to iterate the data.

    Rotations of 90, -90 and 180 degrees are simple transformations which can be performed as long as you know how many rows and columns are in your 2D array; To rotate any vector by 90 degrees, swap the axes and negate the Y axis. For -90 degree, swap the axes and negate the X axis. For 180 degrees, negate both axes without swapping.

    Further transformations are possible, such as mirroring horizontally and/or vertically by negating the axes independently.

    This can be done through e.g. an accessor method. The examples below are JavaScript functions, but the concepts apply equally to all languages.

     // Get an array element in column/row order
     var getArray2d = function(a, x, y) {
       return a[y][x];
     };
    
     //demo
     var arr = [
       [5, 4, 6],
       [1, 7, 9],
       [-2, 11, 0],
       [8, 21, -3],
       [3, -1, 2]
     ];
    
     var newarr = [];
     arr[0].forEach(() => newarr.push(new Array(arr.length)));
    
     for (var i = 0; i < newarr.length; i++) {
       for (var j = 0; j < newarr[0].length; j++) {
         newarr[i][j] = getArray2d(arr, i, j);
       }
     }
     console.log(newarr);

    // Get an array element rotated 90 degrees clockwise
    function getArray2dCW(a, x, y) {
      var t = x;
      x = y;
      y = a.length - t - 1;
      return a[y][x];
    }
    
    //demo
    var arr = [
      [5, 4, 6],
      [1, 7, 9],
      [-2, 11, 0],
      [8, 21, -3],
      [3, -1, 2]
    ];
    
    var newarr = [];
    arr[0].forEach(() => newarr.push(new Array(arr.length)));
    
    for (var i = 0; i < newarr[0].length; i++) {
      for (var j = 0; j < newarr.length; j++) {
        newarr[j][i] = getArray2dCW(arr, i, j);
      }
    }
    console.log(newarr);

    // Get an array element rotated 90 degrees counter-clockwise
    function getArray2dCCW(a, x, y) {
      var t = x;
      x = a[0].length - y - 1;
      y = t;
      return a[y][x];
    }
    
    //demo
    var arr = [
      [5, 4, 6],
      [1, 7, 9],
      [-2, 11, 0],
      [8, 21, -3],
      [3, -1, 2]
    ];
    
    var newarr = [];
    arr[0].forEach(() => newarr.push(new Array(arr.length)));
    
    for (var i = 0; i < newarr[0].length; i++) {
      for (var j = 0; j < newarr.length; j++) {
        newarr[j][i] = getArray2dCCW(arr, i, j);
      }
    }
    console.log(newarr);

    // Get an array element rotated 180 degrees
    function getArray2d180(a, x, y) {
      x = a[0].length - x - 1;
      y = a.length - y - 1;
      return a[y][x];
    }
    
    //demo
    var arr = [
      [5, 4, 6],
      [1, 7, 9],
      [-2, 11, 0],
      [8, 21, -3],
      [3, -1, 2]
    ];
    
    var newarr = [];
    arr.forEach(() => newarr.push(new Array(arr[0].length)));
    
    for (var i = 0; i < newarr[0].length; i++) {
      for (var j = 0; j < newarr.length; j++) {
        newarr[j][i] = getArray2d180(arr, i, j);
      }
    }
    console.log(newarr);

    This code assumes an array of nested arrays, where each inner array is a row.

    The method allows you to read (or write) elements (even in random order) as if the array has been rotated or transformed. Now just pick the right function to call, probably by reference, and away you go!

    The concept can be extended to apply transformations additively (and non-destructively) through the accessor methods. Including arbitrary angle rotations and scaling.

    0 讨论(0)
  • 2020-11-22 03:31
    short normal[4][4] = {{8,4,7,5},{3,4,5,7},{9,5,5,6},{3,3,3,3}};
    
    short rotated[4][4];
    
    for (int r = 0; r < 4; ++r)
    {
      for (int c = 0; c < 4; ++c)
      {
        rotated[r][c] = normal[c][3-r];
      }
    }
    

    Simple C++ method, tho there would be a big memory overhead in a big array.

    0 讨论(0)
  • 2020-11-22 03:32

    Whilst rotating the data in place might be necessary (perhaps to update the physically stored representation), it becomes simpler and possibly more performant to add a layer of indirection onto the array access, perhaps an interface:

    interface IReadableMatrix
    {
        int GetValue(int x, int y);
    }
    

    If your Matrix already implements this interface, then it can be rotated via a decorator class like this:

    class RotatedMatrix : IReadableMatrix
    {
        private readonly IReadableMatrix _baseMatrix;
    
        public RotatedMatrix(IReadableMatrix baseMatrix)
        {
            _baseMatrix = baseMatrix;
        }
    
        int GetValue(int x, int y)
        {
            // transpose x and y dimensions
            return _baseMatrix(y, x);
        }
    }
    

    Rotating +90/-90/180 degrees, flipping horizontally/vertically and scaling can all be achieved in this fashion as well.

    Performance would need to be measured in your specific scenario. However the O(n^2) operation has now been replaced with an O(1) call. It's a virtual method call which is slower than direct array access, so it depends upon how frequently the rotated array is used after rotation. If it's used once, then this approach would definitely win. If it's rotated then used in a long-running system for days, then in-place rotation might perform better. It also depends whether you can accept the up-front cost.

    As with all performance issues, measure, measure, measure!

    0 讨论(0)
  • From a linear point of view, consider the matrices:

        1 2 3        0 0 1
    A = 4 5 6    B = 0 1 0
        7 8 9        1 0 0
    

    Now take A transpose

         1 4 7
    A' = 2 5 8
         3 6 9
    

    And consider the action of A' on B, or B on A'.
    Respectively:

          7 4 1          3 6 9
    A'B = 8 5 2    BA' = 2 5 8
          9 6 3          1 4 7
    

    This is expandable for any n x n matrix. And applying this concept quickly in code:

    void swapInSpace(int** mat, int r1, int c1, int r2, int c2)
    {
        mat[r1][c1] ^= mat[r2][c2];
        mat[r2][c2] ^= mat[r1][c1];
        mat[r1][c1] ^= mat[r2][c2];
    }
    
    void transpose(int** mat, int size)
    {
        for (int i = 0; i < size; i++)
        {
            for (int j = (i + 1); j < size; j++)
            {
                swapInSpace(mat, i, j, j, i);
            }
        }
    }
    
    void rotate(int** mat, int size)
    {
        //Get transpose
        transpose(mat, size);
    
        //Swap columns
        for (int i = 0; i < size / 2; i++)
        {
            for (int j = 0; j < size; j++)
            {
                swapInSpace(mat, i, j, size - (i + 1), j);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:33

    C# code to rotate [n,m] 2D arrays 90 deg right

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MatrixProject
    {
        // mattrix class
    
        class Matrix{
            private int rows;
            private int cols;
            private int[,] matrix;
    
            public Matrix(int n){
                this.rows = n;
                this.cols = n;
                this.matrix = new int[this.rows,this.cols];
    
            }
    
            public Matrix(int n,int m){
                this.rows = n;
                this.cols = m;
    
                this.matrix = new int[this.rows,this.cols];
            }
    
            public void Show()
            {
                for (var i = 0; i < this.rows; i++)
                {
                    for (var j = 0; j < this.cols; j++) {
                        Console.Write("{0,3}", this.matrix[i, j]);
                    }
                    Console.WriteLine();
                }                
            }
    
            public void ReadElements()
            {
               for (var i = 0; i < this.rows; i++)
                    for (var j = 0; j < this.cols; j++)
                    {
                        Console.Write("element[{0},{1}]=",i,j);
                        this.matrix[i, j] = Convert.ToInt32(Console.ReadLine());
                    }            
            }
    
    
            // rotate [n,m] 2D array by 90 deg right
            public void Rotate90DegRight()
            {
    
                // create a mirror of current matrix
                int[,] mirror = this.matrix;
    
                // create a new matrix
                this.matrix = new int[this.cols, this.rows];
    
                for (int i = 0; i < this.rows; i++)
                {
                    for (int j = 0; j < this.cols; j++)
                    {
                        this.matrix[j, this.rows - i - 1] = mirror[i, j];
                    }
                }
    
                // replace cols count with rows count
                int tmp = this.rows;
                this.rows = this.cols;
                this.cols = tmp;           
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Matrix myMatrix = new Matrix(3,4);
                Console.WriteLine("Enter matrix elements:");
                myMatrix.ReadElements();
                Console.WriteLine("Matrix elements are:");
                myMatrix.Show();
                myMatrix.Rotate90DegRight();
                Console.WriteLine("Matrix rotated at 90 deg are:");
                myMatrix.Show();
                Console.ReadLine();
            }
        }
    }
    

    Result:

        Enter matrix elements:
        element[0,0]=1
        element[0,1]=2
        element[0,2]=3
        element[0,3]=4
        element[1,0]=5
        element[1,1]=6
        element[1,2]=7
        element[1,3]=8
        element[2,0]=9
        element[2,1]=10
        element[2,2]=11
        element[2,3]=12
        Matrix elements are:
          1  2  3  4
          5  6  7  8
          9 10 11 12
        Matrix rotated at 90 deg are:
          9  5  1
         10  6  2
         11  7  3
         12  8  4
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题