<p>Inspired by <a href="https://devblogs.microsoft.com/oldnewthing/20080902-00/?p=21003" rel="noreferrer">Raymond Chen's post</a>, 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.</p>

<pre><code>[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
</code></pre>

<p>Becomes:</p>

<pre><code>[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
</code></pre>

<p><strong>Update</strong>: 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?</p>

[{'answer_id': 42535, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 8, 'selected': True, 'text': '<p>Here it is in C#</p>\n\n<pre class="lang-csharp prettyprint-override"><code>int[,] array = new int[4,4] {\n    { 1,2,3,4 },\n    { 5,6,7,8 },\n    { 9,0,1,2 },\n    { 3,4,5,6 }\n};\n\nint[,] rotated = RotateMatrix(array, 4);\n\nstatic int[,] RotateMatrix(int[,] matrix, int n) {\n    int[,] ret = new int[n, n];\n\n    for (int i = 0; i &lt; n; ++i) {\n        for (int j = 0; j &lt; n; ++j) {\n            ret[i, j] = matrix[n - j - 1, i];\n        }\n    }\n\n    return ret;\n}\n</code></pre>\n'}, {'answer_id': 42578, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s my Ruby version (note the values aren\'t displayed the same, but it still rotates as described).</p>\n\n<pre class="lang-ruby prettyprint-override"><code>def rotate(matrix)\n  result = []\n  4.times { |x|\n    result[x] = []\n    4.times { |y|\n      result[x][y] = matrix[y][3 - x]\n    }\n  }\n\n  result\nend\n\nmatrix = []\nmatrix[0] = [1,2,3,4]\nmatrix[1] = [5,6,7,8]\nmatrix[2] = [9,0,1,2]\nmatrix[3] = [3,4,5,6]\n\ndef print_matrix(matrix)\n  4.times { |y|\n    4.times { |x|\n      print "#{matrix[x][y]} "\n    }\n    puts ""\n  }\nend\n\nprint_matrix(matrix)\nputs ""\nprint_matrix(rotate(matrix))\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>1 5 9 3 \n2 6 0 4 \n3 7 1 5 \n4 8 2 6 \n\n4 3 2 1 \n8 7 6 5 \n2 1 0 9 \n6 5 4 3\n</code></pre>\n'}, {'answer_id': 42590, 'author': 'Kevin Berridge', 'author_id': 4407, 'author_profile': 'https://Stackoverflow.com/users/4407', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array#42535">Nick\'s</a> answer would work for an NxM array too with only a small modification (as opposed to an NxN).</p>\n\n<pre class="lang-csharp prettyprint-override"><code>string[,] orig = new string[n, m];\nstring[,] rot = new string[m, n];\n\n...\n\nfor ( int i=0; i &lt; n; i++ )\n  for ( int j=0; j &lt; m; j++ )\n    rot[j, n - i - 1] = orig[i, j];\n</code></pre>\n\n<p>One way to think about this is that you have moved the center of the axis (0,0) from the top left corner to the top right corner.  You\'re simply transposing from one to the other.</p>\n'}, {'answer_id': 42612, 'author': 'nsanders', 'author_id': 1244, 'author_profile': 'https://Stackoverflow.com/users/1244', 'pm_score': 3, 'selected': False, 'text': '<p>A couple of people have already put up examples which involve making a new array.  </p>\n\n<p>A few other things to consider:</p>\n\n<p>(a) Instead of actually moving the data, simply traverse the "rotated" array differently.  </p>\n\n<p>(b) Doing the rotation in-place can be a little trickier.  You\'ll need a bit of scratch place (probably roughly equal to one row or column in size).  There\'s an ancient ACM paper about doing in-place transposes (<a href="http://doi.acm.org/10.1145/355719.355729" rel="noreferrer">http://doi.acm.org/10.1145/355719.355729</a>), but their example code is nasty goto-laden FORTRAN.</p>\n\n<p>Addendum:</p>\n\n<p><a href="http://doi.acm.org/10.1145/355611.355612" rel="noreferrer">http://doi.acm.org/10.1145/355611.355612</a> is another, supposedly superior, in-place transpose algorithm.</p>\n'}, {'answer_id': 43333, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 5, 'selected': False, 'text': '<p>As I said in my previous post, here\'s some code in C# that implements an O(1) matrix rotation for any size matrix. For brevity and readability there\'s no error checking or range checking. The code:</p>\n\n<pre class="lang-csharp prettyprint-override"><code>static void Main (string [] args)\n{\n  int [,]\n    //  create an arbitrary matrix\n    m = {{0, 1}, {2, 3}, {4, 5}};\n\n  Matrix\n    //  create wrappers for the data\n    m1 = new Matrix (m),\n    m2 = new Matrix (m),\n    m3 = new Matrix (m);\n\n  //  rotate the matricies in various ways - all are O(1)\n  m1.RotateClockwise90 ();\n  m2.Rotate180 ();\n  m3.RotateAnitclockwise90 ();\n\n  //  output the result of transforms\n  System.Diagnostics.Trace.WriteLine (m1.ToString ());\n  System.Diagnostics.Trace.WriteLine (m2.ToString ());\n  System.Diagnostics.Trace.WriteLine (m3.ToString ());\n}\n\nclass Matrix\n{\n  enum Rotation\n  {\n    None,\n    Clockwise90,\n    Clockwise180,\n    Clockwise270\n  }\n\n  public Matrix (int [,] matrix)\n  {\n    m_matrix = matrix;\n    m_rotation = Rotation.None;\n  }\n\n  //  the transformation routines\n  public void RotateClockwise90 ()\n  {\n    m_rotation = (Rotation) (((int) m_rotation + 1) &amp; 3);\n  }\n\n  public void Rotate180 ()\n  {\n    m_rotation = (Rotation) (((int) m_rotation + 2) &amp; 3);\n  }\n\n  public void RotateAnitclockwise90 ()\n  {\n    m_rotation = (Rotation) (((int) m_rotation + 3) &amp; 3);\n  }\n\n  //  accessor property to make class look like a two dimensional array\n  public int this [int row, int column]\n  {\n    get\n    {\n      int\n        value = 0;\n\n      switch (m_rotation)\n      {\n      case Rotation.None:\n        value = m_matrix [row, column];\n        break;\n\n      case Rotation.Clockwise90:\n        value = m_matrix [m_matrix.GetUpperBound (0) - column, row];\n        break;\n\n      case Rotation.Clockwise180:\n        value = m_matrix [m_matrix.GetUpperBound (0) - row, m_matrix.GetUpperBound (1) - column];\n        break;\n\n      case Rotation.Clockwise270:\n        value = m_matrix [column, m_matrix.GetUpperBound (1) - row];\n        break;\n      }\n\n      return value;\n    }\n\n    set\n    {\n      switch (m_rotation)\n      {\n      case Rotation.None:\n        m_matrix [row, column] = value;\n        break;\n\n      case Rotation.Clockwise90:\n        m_matrix [m_matrix.GetUpperBound (0) - column, row] = value;\n        break;\n\n      case Rotation.Clockwise180:\n        m_matrix [m_matrix.GetUpperBound (0) - row, m_matrix.GetUpperBound (1) - column] = value;\n        break;\n\n      case Rotation.Clockwise270:\n        m_matrix [column, m_matrix.GetUpperBound (1) - row] = value;\n        break;\n      }\n    }\n  }\n\n  //  creates a string with the matrix values\n  public override string ToString ()\n  {\n    int\n      num_rows = 0,\n      num_columns = 0;\n\n    switch (m_rotation)\n    {\n    case Rotation.None:\n    case Rotation.Clockwise180:\n      num_rows = m_matrix.GetUpperBound (0);\n      num_columns = m_matrix.GetUpperBound (1);\n      break;\n\n    case Rotation.Clockwise90:\n    case Rotation.Clockwise270:\n      num_rows = m_matrix.GetUpperBound (1);\n      num_columns = m_matrix.GetUpperBound (0);\n      break;\n    }\n\n    StringBuilder\n      output = new StringBuilder ();\n\n    output.Append ("{");\n\n    for (int row = 0 ; row &lt;= num_rows ; ++row)\n    {\n      if (row != 0)\n      {\n        output.Append (", ");\n      }\n\n      output.Append ("{");\n\n      for (int column = 0 ; column &lt;= num_columns ; ++column)\n      {\n        if (column != 0)\n        {\n          output.Append (", ");\n        }\n\n        output.Append (this [row, column].ToString ());\n      }\n\n      output.Append ("}");\n    }\n\n    output.Append ("}");\n\n    return output.ToString ();\n  }\n\n  int [,]\n    //  the original matrix\n    m_matrix;\n\n  Rotation\n    //  the current view of the matrix\n    m_rotation;\n}\n</code></pre>\n\n<p>OK, I\'ll put my hand up, it doesn\'t actually do any modifications to the original array when rotating. But, in an OO system that doesn\'t matter as long as the object looks like it\'s been rotated to the clients of the class. At the moment, the Matrix class uses references to the original array data so changing any value of m1 will also change m2 and m3. A small change to the constructor to create a new array and copy the values to it will sort that out.</p>\n'}, {'answer_id': 44368, 'author': 'dagorym', 'author_id': 171, 'author_profile': 'https://Stackoverflow.com/users/171', 'pm_score': 6, 'selected': False, 'text': '<p>Here is one that does the rotation in place instead of using a completely new array to hold the result.  I\'ve left off initialization of the array and printing it out.  This only works for square arrays but they can be of any size.  Memory overhead is equal to the size of one element of the array so you can do the rotation of as large an array as you want.</p>\n\n<pre class="lang-c prettyprint-override"><code>int a[4][4];\nint n = 4;\nint tmp;\nfor (int i = 0; i &lt; n / 2; i++)\n{\n    for (int j = i; j &lt; n - i - 1; j++)\n    {\n        tmp             = a[i][j];\n        a[i][j]         = a[j][n-i-1];\n        a[j][n-i-1]     = a[n-i-1][n-j-1];\n        a[n-i-1][n-j-1] = a[n-j-1][i];\n        a[n-j-1][i]     = tmp;\n    }\n}\n</code></pre>\n'}, {'answer_id': 48607, 'author': 'Nathan Fritz', 'author_id': 4142, 'author_profile': 'https://Stackoverflow.com/users/4142', 'pm_score': 1, 'selected': False, 'text': '<p>@dagorym: Aw, man. I had been hanging onto this as a good "I\'m bored, what can I ponder" puzzle. I came up with my in-place transposition code, but got here to find yours pretty much identical to mine...ah, well. Here it is in Ruby.</p>\n\n<pre class="lang-ruby prettyprint-override"><code>require \'pp\'\nn = 10\na = []\nn.times { a &lt;&lt; (1..n).to_a }\n\npp a\n\n0.upto(n/2-1) do |i|\n  i.upto(n-i-2) do |j|\n    tmp             = a[i][j]\n    a[i][j]         = a[n-j-1][i]\n    a[n-j-1][i]     = a[n-i-1][n-j-1]\n    a[n-i-1][n-j-1] = a[j][n-i-1]\n    a[j][n-i-1]     = tmp\n  end\nend\n\npp a\n</code></pre>\n'}, {'answer_id': 193942, 'author': 'Drew Noakes', 'author_id': 24874, 'author_profile': 'https://Stackoverflow.com/users/24874', 'pm_score': 5, 'selected': False, 'text': '<p>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:</p>\n\n<pre class="lang-csharp prettyprint-override"><code>interface IReadableMatrix\n{\n    int GetValue(int x, int y);\n}\n</code></pre>\n\n<p>If your <code>Matrix</code> already implements this interface, then it can be rotated via a <a href="http://en.wikipedia.org/wiki/Decorator_pattern" rel="noreferrer">decorator</a> class like this:</p>\n\n<pre class="lang-csharp prettyprint-override"><code>class RotatedMatrix : IReadableMatrix\n{\n    private readonly IReadableMatrix _baseMatrix;\n\n    public RotatedMatrix(IReadableMatrix baseMatrix)\n    {\n        _baseMatrix = baseMatrix;\n    }\n\n    int GetValue(int x, int y)\n    {\n        // transpose x and y dimensions\n        return _baseMatrix(y, x);\n    }\n}\n</code></pre>\n\n<p>Rotating +90/-90/180 degrees, flipping horizontally/vertically and scaling can all be achieved in this fashion as well.</p>\n\n<p>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 <em>is</em> 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.</p>\n\n<p>As with all performance issues, measure, measure, measure!</p>\n'}, {'answer_id': 496056, 'author': 'recursive', 'author_id': 44743, 'author_profile': 'https://Stackoverflow.com/users/44743', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Python:</strong></p>\n\n<pre class="lang-py prettyprint-override"><code>rotated = list(zip(*original[::-1]))\n</code></pre>\n\n<p>and counterclockwise:</p>\n\n<pre class="lang-py prettyprint-override"><code>rotated_ccw = list(zip(*original))[::-1]\n</code></pre>\n\n<p><strong>How this works:</strong></p>\n\n<p><code>zip(*original)</code> will swap axes of 2d arrays by stacking corresponding items from lists into new lists. (The <a href="https://docs.python.org/reference/expressions.html#calls" rel="noreferrer"><code>*</code> operator</a> tells the function to distribute the contained lists into arguments)</p>\n\n<pre><code>&gt;&gt;&gt; list(zip(*[[1,2,3],[4,5,6],[7,8,9]]))\n[[1,4,7],[2,5,8],[3,6,9]]\n</code></pre>\n\n<p>The <code>[::-1]</code> statement reverses array elements (please see <a href="https://docs.python.org/2.3/whatsnew/section-slices.html" rel="noreferrer">Extended Slices</a> or <a href="https://stackoverflow.com/questions/509211/understanding-slice-notation">this question</a>):</p>\n\n<pre><code>&gt;&gt;&gt; [[1,2,3],[4,5,6],[7,8,9]][::-1]\n[[7,8,9],[4,5,6],[1,2,3]]\n</code></pre>\n\n<p>Finally, combining the two will result in the rotation transformation.</p>\n\n<p>The change in placement of <code>[::-1]</code> will reverse lists in different levels of the matrix.</p>\n'}, {'answer_id': 768796, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\n\nusing namespace std;\nconst int SIZE=3;\nvoid print(int a[][SIZE],int);\nvoid rotate(int a[][SIZE],int);\n\nvoid main()\n{\n    int a[SIZE][SIZE]={{11,22,33},{44,55,66},{77,88,99}};\n    cout&lt;&lt;"the array befor rotate\\n";\n\n    print(a,SIZE);\n    rotate( a,SIZE);\n    cout&lt;&lt;"the array after rotate\\n";\n    print(a,SIZE);\n    cout&lt;&lt;endl;\n\n}\n\nvoid print(int a[][SIZE],int SIZE)\n{\n    int i,j;\n    for(i=0;i&lt;SIZE;i++)\n       for(j=0;j&lt;SIZE;j++)\n          cout&lt;&lt;a[i][j]&lt;&lt;setw(4);\n}\n\nvoid rotate(int a[][SIZE],int SIZE)\n{\n    int temp[3][3],i,j;\n    for(i=0;i&lt;SIZE;i++)\n       for(j=0;j&lt;SIZE/2.5;j++)\n       {\n           temp[i][j]= a[i][j];\n           a[i][j]= a[j][SIZE-i-1] ;\n           a[j][SIZE-i-1] =temp[i][j];\n\n       }\n}\n</code></pre>\n'}, {'answer_id': 948280, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<pre class="lang-cpp prettyprint-override"><code>short normal[4][4] = {{8,4,7,5},{3,4,5,7},{9,5,5,6},{3,3,3,3}};\n\nshort rotated[4][4];\n\nfor (int r = 0; r &lt; 4; ++r)\n{\n  for (int c = 0; c &lt; 4; ++c)\n  {\n    rotated[r][c] = normal[c][3-r];\n  }\n}\n</code></pre>\n\n<p>Simple C++ method, tho there would be a big memory overhead in a big array.</p>\n'}, {'answer_id': 1092721, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>This a better version of it in Java: I\'ve made it for a matrix with a different width and height</p>\n\n<ul>\n<li>h is here the height of the matrix after rotating</li>\n<li>w is here the width of the matrix after rotating</li>\n</ul>\n\n<p>&nbsp;</p>\n\n<pre class="lang-java prettyprint-override"><code>public int[][] rotateMatrixRight(int[][] matrix)\n{\n    /* W and H are already swapped */\n    int w = matrix.length;\n    int h = matrix[0].length;\n    int[][] ret = new int[h][w];\n    for (int i = 0; i &lt; h; ++i) {\n        for (int j = 0; j &lt; w; ++j) {\n            ret[i][j] = matrix[w - j - 1][i];\n        }\n    }\n    return ret;\n}\n\n\npublic int[][] rotateMatrixLeft(int[][] matrix)\n{\n    /* W and H are already swapped */\n    int w = matrix.length;\n    int h = matrix[0].length;   \n    int[][] ret = new int[h][w];\n    for (int i = 0; i &lt; h; ++i) {\n        for (int j = 0; j &lt; w; ++j) {\n            ret[i][j] = matrix[j][h - i - 1];\n        }\n    }\n    return ret;\n}\n</code></pre>\n\n<p>This code is based on Nick Berardi\'s post.</p>\n'}, {'answer_id': 3137413, 'author': 'James Lin', 'author_id': 342553, 'author_profile': 'https://Stackoverflow.com/users/342553', 'pm_score': 2, 'selected': False, 'text': '<p>PHP:</p>\n\n<pre><code>&lt;?php    \n$a = array(array(1,2,3,4),array(5,6,7,8),array(9,0,1,2),array(3,4,5,6));\n$b = array(); //result\n\nwhile(count($a)&gt;0)\n{\n    $b[count($a[0])-1][] = array_shift($a[0]);\n    if (count($a[0])==0)\n    {\n         array_shift($a);\n    }\n}\n</code></pre>\n\n<p>From PHP5.6, Array transposition can be performed with a sleak <code>array_map()</code> call.  In other words, columns are converted to rows.</p>\n\n<p>Code: (<a href="https://3v4l.org/pIl5n" rel="nofollow noreferrer">Demo</a>)</p>\n\n<pre><code>$array = [\n    [1, 2, 3, 4],\n    [5, 6, 7, 8],\n    [9, 0, 1, 2],\n    [3, 4, 5, 6]\n];\n$transposed = array_map(null, ...$array);\n</code></pre>\n\n<p>$transposed:</p>\n\n<pre><code>[\n    [1, 5, 9, 3],\n    [2, 6, 0, 4],\n    [3, 7, 1, 5],\n    [4, 8, 2, 6]\n]\n</code></pre>\n'}, {'answer_id': 3137649, 'author': 'Clark Gaebel', 'author_id': 105760, 'author_profile': 'https://Stackoverflow.com/users/105760', 'pm_score': 0, 'selected': False, 'text': '<p>All the current solutions have O(n^2) overhead as scratch space (this excludes those filthy OOP cheaters!). Here\'s a solution with O(1) memory usage, rotating the matrix in-place 90 degress right. Screw extensibility, this sucker runs fast!</p>\n\n<pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt;\n#include &lt;cstddef&gt;\n\n// Rotates an NxN matrix of type T 90 degrees to the right.\ntemplate &lt;typename T, size_t N&gt;\nvoid rotate_matrix(T (&amp;matrix)[N][N])\n{\n    for(size_t i = 0; i &lt; N; ++i)\n        for(size_t j = 0; j &lt;= (N-i); ++j)\n            std::swap(matrix[i][j], matrix[j][i]);\n}\n</code></pre>\n\n<p>DISCLAIMER: I didn\'t actually test this. Let\'s play whack-a-bug!</p>\n'}, {'answer_id': 3571501, 'author': 'Nakilon', 'author_id': 322020, 'author_profile': 'https://Stackoverflow.com/users/322020', 'pm_score': 4, 'selected': False, 'text': '<p>Ruby-way: <code>.transpose.map &amp;:reverse</code></p>\n'}, {'answer_id': 8664879, 'author': 'dimple', 'author_id': 1120601, 'author_profile': 'https://Stackoverflow.com/users/1120601', 'pm_score': 9, 'selected': False, 'text': '<p><strong>O(n^2) time and O(1) space algorithm</strong> ( without any workarounds and hanky-panky stuff! )</p>\n\n<p><strong>Rotate by +90:</strong></p>\n\n<ol>\n<li>Transpose</li>\n<li>Reverse each row</li>\n</ol>\n\n<p><strong>Rotate by -90:</strong></p>\n\n<p><em>Method 1 :</em></p>\n\n<ol>\n<li>Transpose</li>\n<li>Reverse each column</li>\n</ol>\n\n<p><em>Method 2 :</em></p>\n\n<ol>\n<li>Reverse each row</li>\n<li>Transpose</li>\n</ol>\n\n<p><strong>Rotate by +180:</strong></p>\n\n<p><em>Method 1</em>: Rotate by +90 twice</p>\n\n<p><em>Method 2</em>: Reverse each row and then reverse each column (Transpose)</p>\n\n<p><strong>Rotate by -180:</strong></p>\n\n<p><em>Method 1</em>: Rotate by -90 twice</p>\n\n<p><em>Method 2</em>: Reverse each column and then reverse each row</p>\n\n<p><em>Method 3</em>: Rotate by +180 as they are same</p>\n'}, {'answer_id': 8668894, 'author': 'Turk', 'author_id': 1121328, 'author_profile': 'https://Stackoverflow.com/users/1121328', 'pm_score': 1, 'selected': False, 'text': '<p><code>For i:= 0 to X do\n       For j := 0 to X do\n               graphic[j][i] := graphic2[X-i][j]</code></p>\n\n<p>X is the size of the array the graphic is in.</p>\n'}, {'answer_id': 9711525, 'author': 'James Yu', 'author_id': 1270299, 'author_profile': 'https://Stackoverflow.com/users/1270299', 'pm_score': 2, 'selected': False, 'text': '<p>here\'s a in-space rotate method, by java, only for square. for non-square 2d array, you will have to create new array anyway.</p>\n\n<pre class="lang-java prettyprint-override"><code>private void rotateInSpace(int[][] arr) {\n    int z = arr.length;\n    for (int i = 0; i &lt; z / 2; i++) {\n        for (int j = 0; j &lt; (z / 2 + z % 2); j++) {\n            int x = i, y = j;\n            int temp = arr[x][y];\n            for (int k = 0; k &lt; 4; k++) {\n                int temptemp = arr[y][z - x - 1];\n                arr[y][z - x - 1] = temp;\n                temp = temptemp;\n\n                int tempX = y;\n                y = z - x - 1;\n                x = tempX;\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>code to rotate any size 2d array by creating new array:</p>\n\n<pre class="lang-java prettyprint-override"><code>private int[][] rotate(int[][] arr) {\n    int width = arr[0].length;\n    int depth = arr.length;\n    int[][] re = new int[width][depth];\n    for (int i = 0; i &lt; depth; i++) {\n        for (int j = 0; j &lt; width; j++) {\n            re[j][depth - i - 1] = arr[i][j];\n        }\n    }\n    return re;\n}\n</code></pre>\n'}, {'answer_id': 10021595, 'author': 'Spidey', 'author_id': 131326, 'author_profile': 'https://Stackoverflow.com/users/131326', 'pm_score': 2, 'selected': False, 'text': '<p>This is my implementation, in C, O(1) memory complexity, in place rotation, 90 degrees clockwise:</p>\n\n<pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;\n\n#define M_SIZE 5\n\nstatic void initMatrix();\nstatic void printMatrix();\nstatic void rotateMatrix();\n\nstatic int m[M_SIZE][M_SIZE];\n\nint main(void){\n    initMatrix();\n    printMatrix();\n    rotateMatrix();\n    printMatrix();\n\n    return 0;\n}\n\nstatic void initMatrix(){\n    int i, j;\n\n    for(i = 0; i &lt; M_SIZE; i++){\n        for(j = 0; j &lt; M_SIZE; j++){\n            m[i][j] = M_SIZE*i + j + 1;\n        }\n    }\n}\n\nstatic void printMatrix(){\n    int i, j;\n\n    printf("Matrix\\n");\n    for(i = 0; i &lt; M_SIZE; i++){\n        for(j = 0; j &lt; M_SIZE; j++){\n            printf("%02d ", m[i][j]);\n        }\n        printf("\\n");\n    }\n    printf("\\n");\n}\n\nstatic void rotateMatrix(){\n    int r, c;\n\n    for(r = 0; r &lt; M_SIZE/2; r++){\n        for(c = r; c &lt; M_SIZE - r - 1; c++){\n            int tmp = m[r][c];\n\n            m[r][c] = m[M_SIZE - c - 1][r];\n            m[M_SIZE - c - 1][r] = m[M_SIZE - r - 1][M_SIZE - c - 1];\n            m[M_SIZE - r - 1][M_SIZE - c - 1] = m[c][M_SIZE - r - 1];\n            m[c][M_SIZE - r - 1] = tmp;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 11695638, 'author': 'k00ka', 'author_id': 3410287, 'author_profile': 'https://Stackoverflow.com/users/3410287', 'pm_score': 1, 'selected': False, 'text': '<p>#transpose is a standard method of Ruby\'s Array class, thus:</p>\n\n<pre><code>% irb\nirb(main):001:0&gt; m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6]]\n=&gt; [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6]] \nirb(main):002:0&gt; m.reverse.transpose\n=&gt; [[3, 9, 5, 1], [4, 0, 6, 2], [5, 1, 7, 3], [6, 2, 8, 4]]\n</code></pre>\n\n<p>The implementation is an n^2 transposition function written in C. You can see it here:\n<a href="http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-transpose" rel="nofollow">http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-transpose</a>\nby choosing "click to toggle source" beside "transpose".</p>\n\n<p>I recall better than O(n^2) solutions, but only for specially constructed matrices (such as sparse matrices)</p>\n'}, {'answer_id': 15073652, 'author': 'rohitmb', 'author_id': 2108332, 'author_profile': 'https://Stackoverflow.com/users/2108332', 'pm_score': 1, 'selected': False, 'text': '<p>C code for matrix rotation 90 degree clockwise IN PLACE for any M*N matrix</p>\n\n<pre class="lang-c prettyprint-override"><code>void rotateInPlace(int * arr[size][size], int row, int column){\n    int i, j;\n    int temp = row&gt;column?row:column;\n    int flipTill = row &lt; column ? row : column;\n    for(i=0;i&lt;flipTill;i++){\n        for(j=0;j&lt;i;j++){\n            swapArrayElements(arr, i, j);\n        }\n    }\n\n    temp = j+1;\n\n    for(i = row&gt;column?i:0; i&lt;row; i++){\n            for(j=row&lt;column?temp:0; j&lt;column; j++){\n                swapArrayElements(arr, i, j);\n            }\n    }\n\n    for(i=0;i&lt;column;i++){\n        for(j=0;j&lt;row/2;j++){\n            temp = arr[i][j];\n            arr[i][j] = arr[i][row-j-1];\n            arr[i][row-j-1] = temp;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 15432619, 'author': 'user1596193', 'author_id': 1596193, 'author_profile': 'https://Stackoverflow.com/users/1596193', 'pm_score': 1, 'selected': False, 'text': '<p>Here is my attempt for matrix 90 deg rotation which is a 2 step solution in C. First transpose the matrix in place and then swap the cols.</p>\n\n<pre class="lang-c prettyprint-override"><code>#define ROWS        5\n#define COLS        5\n\nvoid print_matrix_b(int B[][COLS], int rows, int cols) \n{\n    for (int i = 0; i &lt;= rows; i++) {\n        for (int j = 0; j &lt;=cols; j++) {\n            printf("%d ", B[i][j]);\n        }\n        printf("\\n");\n    }\n}\n\nvoid swap_columns(int B[][COLS], int l, int r, int rows)\n{\n    int tmp;\n    for (int i = 0; i &lt;= rows; i++) {\n        tmp = B[i][l];\n        B[i][l] = B[i][r];\n        B[i][r] = tmp;\n    }\n}\n\n\nvoid matrix_2d_rotation(int B[][COLS], int rows, int cols)\n{\n    int tmp;\n    // Transpose the matrix first\n    for (int i = 0; i &lt;= rows; i++) {\n        for (int j = i; j &lt;=cols; j++) {\n            tmp = B[i][j];\n            B[i][j] = B[j][i];\n            B[j][i] = tmp;\n        }\n    }\n    // Swap the first and last col and continue until\n    // the middle.\n    for (int i = 0; i &lt; (cols / 2); i++)\n        swap_columns(B, i, cols - i, rows);\n}\n\n\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    int B[ROWS][COLS] = { \n                  {1, 2, 3, 4, 5}, \n                      {6, 7, 8, 9, 10},\n                          {11, 12, 13, 14, 15},\n                          {16, 17, 18, 19, 20},\n                          {21, 22, 23, 24, 25}\n                        };\n\n    matrix_2d_rotation(B, ROWS - 1, COLS - 1);\n\n    print_matrix_b(B, ROWS - 1, COLS -1);\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 15501334, 'author': 'ramon.liu', 'author_id': 2025792, 'author_profile': 'https://Stackoverflow.com/users/2025792', 'pm_score': -1, 'selected': False, 'text': "<p>The O(1) memory algorithm:</p>\n\n<ol>\n<li><p>rotate the outer-most data, then you can get below result:</p>\n\n<pre><code>[3][9][5][1]\n[4][6][7][2]\n[5][0][1][3]\n[6][2][8][4]\n</code></pre></li>\n</ol>\n\n<p>To do this rotation, we know </p>\n\n<pre><code>    dest[j][n-1-i] = src[i][j]\n</code></pre>\n\n<p>Observe below: \n        a(0,0) -> a(0,3)\n        a(0,3) -> a(3,3)\n        a(3,3) -> a(3,0)\n        a(3,0) -> a(0,0)</p>\n\n<p>Therefore it's a circle, you can rotate N elements in one loop. Do this N-1 loop then you can rotate the outer-most elements.</p>\n\n<ol>\n<li>Now you can the inner is a same question for 2X2. </li>\n</ol>\n\n<p>Therefore we can conclude it like below:</p>\n\n<pre><code>function rotate(array, N)\n{\n    Rotate outer-most data\n    rotate a new array with N-2 or you can do the similar action following step1\n}\n</code></pre>\n"}, {'answer_id': 16661397, 'author': 'radium', 'author_id': 1642753, 'author_profile': 'https://Stackoverflow.com/users/1642753', 'pm_score': 2, 'selected': False, 'text': '<p>Here is the Java version:</p>\n\n<pre class="lang-java prettyprint-override"><code>public static void rightRotate(int[][] matrix, int n) {\n    for (int layer = 0; layer &lt; n / 2; layer++) {\n        int first = layer;\n        int last = n - 1 - first;\n        for (int i = first; i &lt; last; i++) {\n           int offset = i - first;\n           int temp = matrix[first][i];\n           matrix[first][i] = matrix[last-offset][first];\n           matrix[last-offset][first] = matrix[last][last-offset];\n           matrix[last][last-offset] = matrix[i][last];\n           matrix[i][last] = temp;\n        }\n    }\n}\n</code></pre>\n\n<p>the method first rotate the mostouter layer, then move to the inner layer squentially.</p>\n'}, {'answer_id': 18013355, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<pre class="lang-java prettyprint-override"><code>private static int[][] rotate(int[][] matrix, int n) {\n    int[][] rotated = new int[n][n];\n    for (int i = 0; i &lt; n; i++) {\n        for (int j = 0; j &lt; n; j++) {\n            rotated[i][j] = matrix[n-j-1][i];\n        }\n    }\n    return rotated;\n}\n</code></pre>\n'}, {'answer_id': 18215843, 'author': 'thiagoh', 'author_id': 889213, 'author_profile': 'https://Stackoverflow.com/users/889213', 'pm_score': 1, 'selected': False, 'text': '<p>here is my In Place implementation in C</p>\n\n<pre class="lang-c prettyprint-override"><code>void rotateRight(int matrix[][SIZE], int length) {\n\n    int layer = 0;\n\n    for (int layer = 0; layer &lt; length / 2; ++layer) {\n\n        int first = layer;\n        int last = length - 1 - layer;\n\n        for (int i = first; i &lt; last; ++i) {\n\n            int topline = matrix[first][i];\n            int rightcol = matrix[i][last];\n            int bottomline = matrix[last][length - layer - 1 - i];\n            int leftcol = matrix[length - layer - 1 - i][first];\n\n            matrix[first][i] = leftcol;\n            matrix[i][last] = topline;\n            matrix[last][length - layer - 1 - i] = rightcol;\n            matrix[length - layer - 1 - i][first] = bottomline;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 18262380, 'author': 'mhawksey', 'author_id': 1027723, 'author_profile': 'https://Stackoverflow.com/users/1027723', 'pm_score': 2, 'selected': False, 'text': '<p>Implementation of dimple\'s +90 pseudocode (e.g. transpose then reverse each row) in JavaScript:</p>\n\n<pre class="lang-js prettyprint-override"><code>function rotate90(a){\n  // transpose from http://www.codesuck.com/2012/02/transpose-javascript-array-in-one-line.html\n  a = Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });\n  // row reverse\n  for (i in a){\n    a[i] = a[i].reverse();\n  }\n  return a;\n}\n</code></pre>\n'}, {'answer_id': 20199933, 'author': 'tweaking', 'author_id': 2716562, 'author_profile': 'https://Stackoverflow.com/users/2716562', 'pm_score': 5, 'selected': False, 'text': "<p>There are tons of good code here but I just want to show what's going on geometrically so you can understand the code logic a little better.  Here is how I would approach this.</p>\n\n<p>first of all, do not confuse this with transposition which is very easy..</p>\n\n<p>the basica idea is to treat it as layers and we rotate one layer at a time..</p>\n\n<p>say we have a 4x4</p>\n\n<pre><code>1   2   3   4\n5   6   7   8\n9   10  11  12\n13  14  15  16\n</code></pre>\n\n<p>after we rotate it clockwise by 90 we get</p>\n\n<pre><code>13  9   5   1\n14  10  6   2   \n15  11  7   3\n16  12  8   4\n</code></pre>\n\n<p>so let's decompose this, first we rotate the 4 corners essentially</p>\n\n<pre><code>1           4\n\n\n13          16\n</code></pre>\n\n<p>then we rotate the following diamond which is sort of askew</p>\n\n<pre><code>    2\n            8\n9       \n        15\n</code></pre>\n\n<p>and then the 2nd skewed diamond</p>\n\n<pre><code>        3\n5           \n            12\n    14\n</code></pre>\n\n<p>so that takes care of the outer edge so essentially we do that one shell at a time until </p>\n\n<p>finally the middle square (or if it's odd just the final element which does not move)</p>\n\n<pre><code>6   7\n10  11\n</code></pre>\n\n<p>so now let's figure out the indices of each layer, assume we always work with the outermost layer, we are doing</p>\n\n<pre><code>[0,0] -&gt; [0,n-1], [0,n-1] -&gt; [n-1,n-1], [n-1,n-1] -&gt; [n-1,0], and [n-1,0] -&gt; [0,0]\n[0,1] -&gt; [1,n-1], [1,n-2] -&gt; [n-1,n-2], [n-1,n-2] -&gt; [n-2,0], and [n-2,0] -&gt; [0,1]\n[0,2] -&gt; [2,n-2], [2,n-2] -&gt; [n-1,n-3], [n-1,n-3] -&gt; [n-3,0], and [n-3,0] -&gt; [0,2]\n</code></pre>\n\n<p>so on and so on\nuntil we are halfway through the edge</p>\n\n<p>so in general the pattern is </p>\n\n<pre><code>[0,i] -&gt; [i,n-i], [i,n-i] -&gt; [n-1,n-(i+1)], [n-1,n-(i+1)] -&gt; [n-(i+1),0], and [n-(i+1),0] to [0,i]\n</code></pre>\n"}, {'answer_id': 20202797, 'author': 'user3000711', 'author_id': 3000711, 'author_profile': 'https://Stackoverflow.com/users/3000711', 'pm_score': -1, 'selected': False, 'text': '<p>It is not possible to do it quicker than O(n^2) for in place rotation, for the reason that if we want to rotate the matrix, we have to touch all the n^2 element at least once, no matter what algorithm you are implementing.</p>\n'}, {'answer_id': 21265476, 'author': 'user2793692', 'author_id': 2793692, 'author_profile': 'https://Stackoverflow.com/users/2793692', 'pm_score': 3, 'selected': False, 'text': '<p>Time - O(N), Space - O(1)</p>\n\n<pre><code>public void rotate(int[][] matrix) {\n    int n = matrix.length;\n    for (int i = 0; i &lt; n / 2; i++) {\n        int last = n - 1 - i;\n        for (int j = i; j &lt; last; j++) {\n            int top = matrix[i][j];\n            matrix[i][j] = matrix[last - j][i];\n            matrix[last - j][i] = matrix[last][last - j];\n            matrix[last][last - j] = matrix[j][last];\n            matrix[j][last] = top;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 21977882, 'author': 'taxicala', 'author_id': 2988337, 'author_profile': 'https://Stackoverflow.com/users/2988337', 'pm_score': 0, 'selected': False, 'text': "<p>Here is a recursive PHP way:</p>\n\n<pre><code>$m = array();\n            $m[0] = array('a', 'b', 'c');\n            $m[1] = array('d', 'e', 'f');\n            $m[2] = array('g', 'h', 'i');\n            $newMatrix = array();\n\n            function rotateMatrix($m, $i = 0, &amp;$newMatrix)\n            {\n                foreach ($m as $chunk) {\n                    $newChunk[] = $chunk[$i];\n                }\n                $newMatrix[] = array_reverse($newChunk);\n                $i++;\n\n                if ($i &lt; count($m)) {\n                    rotateMatrix($m, $i, $newMatrix);\n                }\n            }\n\n            rotateMatrix($m, 0, $newMatrix);\n            echo '&lt;pre&gt;';\n            var_dump($newMatrix);\n            echo '&lt;pre&gt;';\n</code></pre>\n"}, {'answer_id': 22858585, 'author': 'Alex', 'author_id': 3497339, 'author_profile': 'https://Stackoverflow.com/users/3497339', 'pm_score': 0, 'selected': False, 'text': '<p>My version of rotation:</p>\n\n<pre><code>void rotate_matrix(int *matrix, int size)\n{\n\nint result[size*size];\n\n    for (int i = 0; i &lt; size; ++i)\n        for (int j = 0; j &lt; size; ++j)\n            result[(size - 1 - i) + j*size] = matrix[i*size+j];\n\n    for (int i = 0; i &lt; size*size; ++i)\n        matrix[i] = result[i];\n}\n</code></pre>\n\n<p>In it we change last column to first row and so further. It is may be not optimal but clear for understanding.</p>\n'}, {'answer_id': 23486371, 'author': 'user4964091', 'author_id': 4964091, 'author_profile': 'https://Stackoverflow.com/users/4964091', 'pm_score': -1, 'selected': False, 'text': '<p><strong>For Novice programmers, in plain C++ . (Borland stuff)</strong>   </p>\n\n<pre><code>#include&lt;iostream.h&gt;\n#include&lt;conio.h&gt;\n\nint main()\n{\n    clrscr();\n\n    int arr[10][10];        // 2d array that holds input elements \n    int result[10][10];     //holds result\n\n    int m,n;                //rows and columns of arr[][]\n    int x,y;                //rows and columns of result[][]\n\n    int i,j;                //loop variables\n    int t;                  //temporary , holds data while conversion\n\n    cout&lt;&lt;"Enter no. of rows and columns of array: ";\n    cin&gt;&gt;m&gt;&gt;n;\n    cout&lt;&lt;"\\nEnter elements of array: \\n\\n";\n    for(i = 0; i &lt; m; i++)\n    {\n        for(j = 0; j&lt;n ; j++)\n        {\n          cin&gt;&gt;arr[i][j];         // input array elements from user\n        }\n    }\n\n\n   //rotating matrix by +90 degrees\n\n    x = n ;                      //for non-square matrix\n    y = m ;     \n\n    for(i = 0; i &lt; x; i++)\n    {  t = m-1;                     // to create required array bounds\n       for(j = 0; j &lt; y; j++)\n       {\n          result[i][j] = arr[t][i];\n          t--;\n       }\n   }\n\n   //print result\n\n   cout&lt;&lt;"\\nRotated matrix is: \\n\\n";\n   for(i = 0; i &lt; x; i++)\n   {\n       for(j = 0; j &lt; y; j++)\n       {\n             cout&lt;&lt;result[i][j]&lt;&lt;" ";\n       }\n       cout&lt;&lt;"\\n";\n   }\n\n   getch();\n   return 0;\n}\n</code></pre>\n'}, {'answer_id': 24356420, 'author': 'Paul Calabro', 'author_id': 517137, 'author_profile': 'https://Stackoverflow.com/users/517137', 'pm_score': -1, 'selected': False, 'text': "<pre><code>#!/usr/bin/env python\n\noriginal = [ [1,2,3],\n             [4,5,6],\n             [7,8,9] ]\n\n# Rotate matrix 90 degrees...\nfor i in map(None,*original[::-1]):\n    print str(i) + '\\n'\n</code></pre>\n\n<p>This causes the sides to be rotated 90 degrees (ie. 123 (top side) is now 741 (left side).</p>\n\n<p>This Python solution works because it uses slicing with a negative step to reverse the row orders (bringing 7 to top)</p>\n\n<pre><code>original = [ [7,8,9],\n             [4,5,6],\n             [1,2,3] ]\n</code></pre>\n\n<p>It then uses map (along with the implied identity function which is the result of map with None as first arg) along with * to unpack all elements in sequence, to regroup the columns (ie. the first elements are put in a tuple together, the 2nd elements are put in a tuple together, and so forth). You effectively get get returned the following regrouping:</p>\n\n<pre><code>original = [[7,8,9],\n             [4,5,6],\n             [1,2,3]]\n</code></pre>\n"}, {'answer_id': 26180084, 'author': 'obotezat', 'author_id': 373108, 'author_profile': 'https://Stackoverflow.com/users/373108', 'pm_score': -1, 'selected': False, 'text': '<p><strong>PHP:</strong></p>\n\n<pre><code>array_unshift($array, null);\n$array = call_user_func_array("array_map", $array);\n</code></pre>\n\n<p>If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:</p>\n\n<pre><code>$array = array_reverse($array);\n</code></pre>\n'}, {'answer_id': 26320746, 'author': 'Mr. Nex', 'author_id': 3680827, 'author_profile': 'https://Stackoverflow.com/users/3680827', 'pm_score': 2, 'selected': False, 'text': "<p>From a linear point of view, consider the matrices:</p>\n\n<pre><code>    1 2 3        0 0 1\nA = 4 5 6    B = 0 1 0\n    7 8 9        1 0 0\n</code></pre>\n\n<p>Now take A transpose</p>\n\n<pre><code>     1 4 7\nA' = 2 5 8\n     3 6 9\n</code></pre>\n\n<p>And consider the action of A' on B, or B on A'.<br>\nRespectively:</p>\n\n<pre><code>      7 4 1          3 6 9\nA'B = 8 5 2    BA' = 2 5 8\n      9 6 3          1 4 7\n</code></pre>\n\n<p>This is expandable for any n x n matrix.\nAnd applying this concept quickly in code:</p>\n\n<pre><code>void swapInSpace(int** mat, int r1, int c1, int r2, int c2)\n{\n    mat[r1][c1] ^= mat[r2][c2];\n    mat[r2][c2] ^= mat[r1][c1];\n    mat[r1][c1] ^= mat[r2][c2];\n}\n\nvoid transpose(int** mat, int size)\n{\n    for (int i = 0; i &lt; size; i++)\n    {\n        for (int j = (i + 1); j &lt; size; j++)\n        {\n            swapInSpace(mat, i, j, j, i);\n        }\n    }\n}\n\nvoid rotate(int** mat, int size)\n{\n    //Get transpose\n    transpose(mat, size);\n\n    //Swap columns\n    for (int i = 0; i &lt; size / 2; i++)\n    {\n        for (int j = 0; j &lt; size; j++)\n        {\n            swapInSpace(mat, i, j, size - (i + 1), j);\n        }\n    }\n}\n</code></pre>\n"}, {'answer_id': 26374543, 'author': 'Jason Oster', 'author_id': 466030, 'author_profile': 'https://Stackoverflow.com/users/466030', 'pm_score': 4, 'selected': False, 'text': '<p>There are a lot of answers already, and I found two claiming O(1) time complexity. The <strong>real</strong> 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.</p>\n\n<p>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.</p>\n\n<p>Further transformations are possible, such as mirroring horizontally and/or vertically by negating the axes independently.</p>\n\n<p>This can be done through e.g. an accessor method. The examples below are JavaScript functions, but the concepts apply equally to all languages.</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code> // Get an array element in column/row order\r\n var getArray2d = function(a, x, y) {\r\n   return a[y][x];\r\n };\r\n\r\n //demo\r\n var arr = [\r\n   [5, 4, 6],\r\n   [1, 7, 9],\r\n   [-2, 11, 0],\r\n   [8, 21, -3],\r\n   [3, -1, 2]\r\n ];\r\n\r\n var newarr = [];\r\n arr[0].forEach(() =&gt; newarr.push(new Array(arr.length)));\r\n\r\n for (var i = 0; i &lt; newarr.length; i++) {\r\n   for (var j = 0; j &lt; newarr[0].length; j++) {\r\n     newarr[i][j] = getArray2d(arr, i, j);\r\n   }\r\n }\r\n console.log(newarr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>// Get an array element rotated 90 degrees clockwise\r\nfunction getArray2dCW(a, x, y) {\r\n  var t = x;\r\n  x = y;\r\n  y = a.length - t - 1;\r\n  return a[y][x];\r\n}\r\n\r\n//demo\r\nvar arr = [\r\n  [5, 4, 6],\r\n  [1, 7, 9],\r\n  [-2, 11, 0],\r\n  [8, 21, -3],\r\n  [3, -1, 2]\r\n];\r\n\r\nvar newarr = [];\r\narr[0].forEach(() =&gt; newarr.push(new Array(arr.length)));\r\n\r\nfor (var i = 0; i &lt; newarr[0].length; i++) {\r\n  for (var j = 0; j &lt; newarr.length; j++) {\r\n    newarr[j][i] = getArray2dCW(arr, i, j);\r\n  }\r\n}\r\nconsole.log(newarr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>// Get an array element rotated 90 degrees counter-clockwise\r\nfunction getArray2dCCW(a, x, y) {\r\n  var t = x;\r\n  x = a[0].length - y - 1;\r\n  y = t;\r\n  return a[y][x];\r\n}\r\n\r\n//demo\r\nvar arr = [\r\n  [5, 4, 6],\r\n  [1, 7, 9],\r\n  [-2, 11, 0],\r\n  [8, 21, -3],\r\n  [3, -1, 2]\r\n];\r\n\r\nvar newarr = [];\r\narr[0].forEach(() =&gt; newarr.push(new Array(arr.length)));\r\n\r\nfor (var i = 0; i &lt; newarr[0].length; i++) {\r\n  for (var j = 0; j &lt; newarr.length; j++) {\r\n    newarr[j][i] = getArray2dCCW(arr, i, j);\r\n  }\r\n}\r\nconsole.log(newarr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>// Get an array element rotated 180 degrees\r\nfunction getArray2d180(a, x, y) {\r\n  x = a[0].length - x - 1;\r\n  y = a.length - y - 1;\r\n  return a[y][x];\r\n}\r\n\r\n//demo\r\nvar arr = [\r\n  [5, 4, 6],\r\n  [1, 7, 9],\r\n  [-2, 11, 0],\r\n  [8, 21, -3],\r\n  [3, -1, 2]\r\n];\r\n\r\nvar newarr = [];\r\narr.forEach(() =&gt; newarr.push(new Array(arr[0].length)));\r\n\r\nfor (var i = 0; i &lt; newarr[0].length; i++) {\r\n  for (var j = 0; j &lt; newarr.length; j++) {\r\n    newarr[j][i] = getArray2d180(arr, i, j);\r\n  }\r\n}\r\nconsole.log(newarr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This code assumes an array of nested arrays, where each inner array is a row.</p>\n\n<p>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!</p>\n\n<p>The concept can be extended to apply transformations additively (and non-destructively) through the accessor methods. Including arbitrary angle rotations and scaling.</p>\n'}, {'answer_id': 27161656, 'author': 'spark', 'author_id': 4279802, 'author_profile': 'https://Stackoverflow.com/users/4279802', 'pm_score': -1, 'selected': False, 'text': '<p>JavaScript solution to rotate matrix by 90 degrees in place:</p>\n\n<pre><code>function rotateBy90(m) {\n  var length = m.length;\n  //for each layer of the matrix\n  for (var first = 0; first &lt; length &gt;&gt; 1; first++) {\n    var last = length - 1 - first;\n    for (var i = first; i &lt; last; i++) {\n      var top = m[first][i]; //store top\n      m[first][i] = m[last - i][first]; //top = left\n      m[last - i][first] = m[last][last - i]; //left = bottom\n      m[last][last - i] = m[i][last]; //bottom = right\n      m[i][last] = top; //right = top\n    }\n  }\n  return m;\n}\n</code></pre>\n'}, {'answer_id': 28610081, 'author': 'ustmaestro', 'author_id': 2624626, 'author_profile': 'https://Stackoverflow.com/users/2624626', 'pm_score': 2, 'selected': False, 'text': '<p>C# code to rotate [n,m] 2D arrays 90 deg right</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace MatrixProject\n{\n    // mattrix class\n\n    class Matrix{\n        private int rows;\n        private int cols;\n        private int[,] matrix;\n\n        public Matrix(int n){\n            this.rows = n;\n            this.cols = n;\n            this.matrix = new int[this.rows,this.cols];\n\n        }\n\n        public Matrix(int n,int m){\n            this.rows = n;\n            this.cols = m;\n\n            this.matrix = new int[this.rows,this.cols];\n        }\n\n        public void Show()\n        {\n            for (var i = 0; i &lt; this.rows; i++)\n            {\n                for (var j = 0; j &lt; this.cols; j++) {\n                    Console.Write("{0,3}", this.matrix[i, j]);\n                }\n                Console.WriteLine();\n            }                \n        }\n\n        public void ReadElements()\n        {\n           for (var i = 0; i &lt; this.rows; i++)\n                for (var j = 0; j &lt; this.cols; j++)\n                {\n                    Console.Write("element[{0},{1}]=",i,j);\n                    this.matrix[i, j] = Convert.ToInt32(Console.ReadLine());\n                }            \n        }\n\n\n        // rotate [n,m] 2D array by 90 deg right\n        public void Rotate90DegRight()\n        {\n\n            // create a mirror of current matrix\n            int[,] mirror = this.matrix;\n\n            // create a new matrix\n            this.matrix = new int[this.cols, this.rows];\n\n            for (int i = 0; i &lt; this.rows; i++)\n            {\n                for (int j = 0; j &lt; this.cols; j++)\n                {\n                    this.matrix[j, this.rows - i - 1] = mirror[i, j];\n                }\n            }\n\n            // replace cols count with rows count\n            int tmp = this.rows;\n            this.rows = this.cols;\n            this.cols = tmp;           \n        }\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Matrix myMatrix = new Matrix(3,4);\n            Console.WriteLine("Enter matrix elements:");\n            myMatrix.ReadElements();\n            Console.WriteLine("Matrix elements are:");\n            myMatrix.Show();\n            myMatrix.Rotate90DegRight();\n            Console.WriteLine("Matrix rotated at 90 deg are:");\n            myMatrix.Show();\n            Console.ReadLine();\n        }\n    }\n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>    Enter matrix elements:\n    element[0,0]=1\n    element[0,1]=2\n    element[0,2]=3\n    element[0,3]=4\n    element[1,0]=5\n    element[1,1]=6\n    element[1,2]=7\n    element[1,3]=8\n    element[2,0]=9\n    element[2,1]=10\n    element[2,2]=11\n    element[2,3]=12\n    Matrix elements are:\n      1  2  3  4\n      5  6  7  8\n      9 10 11 12\n    Matrix rotated at 90 deg are:\n      9  5  1\n     10  6  2\n     11  7  3\n     12  8  4\n</code></pre>\n'}, {'answer_id': 31079886, 'author': 'Shiva', 'author_id': 5054208, 'author_profile': 'https://Stackoverflow.com/users/5054208', 'pm_score': -1, 'selected': False, 'text': '<pre><code>/* 90-degree clockwise:\n   temp_array         = left_col\n   left_col           = bottom_row\n   bottom_row         = reverse(right_col)\n   reverse(right_col) = reverse(top_row)\n   reverse(top_row)   = temp_array\n*/\nvoid RotateClockwise90(int ** arr, int lo, int hi) {\n\n  if (lo &gt;= hi) \n    return;\n\n  for (int i=lo; i&lt;hi; i++) {\n    int j = lo+hi-i;\n    int temp   = arr[i][lo];\n    arr[i][lo] = arr[hi][i];\n    arr[hi][i] = arr[j][hi];\n    arr[j][hi] = arr[lo][j];\n    arr[lo][j] = temp;\n  }\n\n  RotateClockwise90(arr, lo+1, hi-1);\n}\n</code></pre>\n'}, {'answer_id': 31904916, 'author': 'asad_nitp', 'author_id': 5066038, 'author_profile': 'https://Stackoverflow.com/users/5066038', 'pm_score': -1, 'selected': False, 'text': '<p>In place clock wise 90 degrees rotation using vector of vectors..</p>\n\n<pre><code> #include&lt;iostream&gt;\n #include&lt;vector&gt;\n #include&lt;algorithm&gt;\n using namespace std;\n //Rotate a Matrix by 90 degrees\nvoid rotateMatrix(vector&lt;vector&lt;int&gt; &gt; &amp;matrix){\n   int n=matrix.size();\n   for(int i=0;i&lt;n;i++){\n    for(int j=i+1;j&lt;n;j++){\n        swap(matrix[i][j],matrix[j][i]);\n    }\n }\n     for(int i=0;i&lt;n;i++){\n        reverse(matrix[i].begin(),matrix[i].end());\n       }\n   }\n\n    int main(){\n\n   int n;\n   cout&lt;&lt;"enter the size of the matrix:"&lt;&lt;endl;\n     while (cin &gt;&gt; n) {\n    vector&lt; vector&lt;int&gt; &gt; m;\n      cout&lt;&lt;"enter the elements"&lt;&lt;endl;\n    for (int i = 0; i &lt; n; i++) {\n        m.push_back(vector&lt;int&gt;(n));\n        for (int j = 0; j &lt; n; j++)\n            scanf("%d", &amp;m[i][j]);\n    }\n      cout&lt;&lt;"the rotated matrix is:"&lt;&lt;endl;\n      rotateMatrix(m);\n    for (int i = 0; i &lt; n; i++) {\n        for (int j = 0; j &lt; n; j++)\n            cout &lt;&lt; m[i][j] &lt;&lt; \' \';\n        cout &lt;&lt; endl;\n    }\n   }\n   return 0;\n }\n</code></pre>\n'}, {'answer_id': 32344382, 'author': 'Shawn', 'author_id': 404760, 'author_profile': 'https://Stackoverflow.com/users/404760', 'pm_score': 1, 'selected': False, 'text': '<p>Javascript solution for NxN matrix with runtime O(N^2) and memory O(1)</p>\n\n<pre><code>  function rotate90(matrix){\n    var length = matrix.length\n    for(var row = 0; row &lt; (length / 2); row++){\n      for(var col = row; col &lt; ( length - 1 - row); col++){\n        var tmpVal = matrix[row][col];\n        for(var i = 0; i &lt; 4; i++){\n          var rowSwap = col;\n          var colSwap = (length - 1) - row;\n          var poppedVal = matrix[rowSwap][colSwap];\n          matrix[rowSwap][colSwap] = tmpVal;\n          tmpVal = poppedVal;\n          col = colSwap;\n          row = rowSwap;\n        }\n      }\n    }\n  }\n</code></pre>\n'}, {'answer_id': 32940678, 'author': 'gmohim', 'author_id': 4856100, 'author_profile': 'https://Stackoverflow.com/users/4856100', 'pm_score': -1, 'selected': False, 'text': '<p>This is an overrated interview question these days.</p>\n\n<p>My suggestion is: Do not let the interviewer confuse you with their crazy suggestion about solving this problem. Use the whiteboard to draw the indexing of input array then draw the indexing of output array. Samples of column indexing before and after rotation shown below:</p>\n\n<pre><code>30 --&gt; 00\n20 --&gt; 01\n10 --&gt; 02\n00 --&gt; 03\n\n31 --&gt; 10\n21 --&gt; 11\n11 --&gt; 12\n01 --&gt; 13\n</code></pre>\n\n<p>Notice the number pattern after rotation.</p>\n\n<p>Provided below a clean cut Java solution. It is tested, and it works:</p>\n\n<pre><code> Input:\n    M A C P \n    B N L D \n    Y E T S \n    I W R Z \n\n    Output:\n    I Y B M \n    W E N A \n    R T L C \n    Z S D P \n\n/**\n * (c) @author "G A N MOHIM"\n * Oct 3, 2015\n * RotateArrayNintyDegree.java\n */\npackage rotatearray;\n\npublic class RotateArrayNintyDegree {\n\n    public char[][] rotateArrayNinetyDegree(char[][] input) {\n        int k; // k is used to generate index for output array\n\n        char[][] output = new char[input.length] [input[0].length];\n\n        for (int i = 0; i &lt; input.length; i++) {\n            k = 0;\n            for (int j = input.length-1; j &gt;= 0; j--) {\n                output[i][k] = input[j][i]; // note how i is used as column index, and j as row\n                k++;\n            }\n        }\n\n        return output;\n    }\n\n    public void printArray(char[][] charArray) {\n        for (int i = 0; i &lt; charArray.length; i++) {\n            for (int j = 0; j &lt; charArray[0].length; j++) {\n                System.out.print(charArray[i][j] + " ");\n            }\n            System.out.println();\n        }\n\n\n    }\n\n    public static void main(String[] args) {\n        char[][] input = \n                { {\'M\', \'A\', \'C\', \'P\'},\n                  {\'B\', \'N\', \'L\', \'D\'},\n                  {\'Y\', \'E\', \'T\', \'S\'},\n                  {\'I\', \'W\', \'R\', \'Z\'}\n                };\n\n        char[][] output = new char[input.length] [input[0].length];\n\n        RotateArrayNintyDegree rotationObj = new RotateArrayNintyDegree();\n        rotationObj.printArray(input);\n\n        System.out.println("\\n");\n        output = rotationObj.rotateArrayNinetyDegree(input);\n        rotationObj.printArray(output);\n\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 34534812, 'author': 'Prateek Joshi', 'author_id': 4281711, 'author_profile': 'https://Stackoverflow.com/users/4281711', 'pm_score': 2, 'selected': False, 'text': '<p>You can do this in <strong>3 easy steps</strong>:</p>\n\n<p><strong>1</strong>)Suppose we have a matrix</p>\n\n<pre><code>   1 2 3\n   4 5 6\n   7 8 9\n</code></pre>\n\n<p><strong>2</strong>)Take the transpose of the matrix</p>\n\n<pre><code>   1 4 7\n   2 5 8\n   3 6 9\n</code></pre>\n\n<p><strong>3</strong>)Interchange rows to get rotated matrix</p>\n\n<pre><code>   3 6 9\n   2 5 8\n   1 4 7\n</code></pre>\n\n<p><strong><em>Java</em> source code</strong> for this:</p>\n\n<pre><code>public class MyClass {\n\n    public static void main(String args[]) {\n        Demo obj = new Demo();\n        /*initial matrix to rotate*/\n        int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };\n        int[][] transpose = new int[3][3]; // matrix to store transpose\n\n        obj.display(matrix);              // initial matrix\n\n        obj.rotate(matrix, transpose);    // call rotate method\n        System.out.println();\n        obj.display(transpose);           // display the rotated matix\n    }\n}\n\nclass Demo {   \n    public void rotate(int[][] mat, int[][] tran) {\n\n        /* First take the transpose of the matrix */\n        for (int i = 0; i &lt; mat.length; i++) {\n            for (int j = 0; j &lt; mat.length; j++) {\n                tran[i][j] = mat[j][i]; \n            }\n        }\n\n        /*\n         * Interchange the rows of the transpose matrix to get rotated\n         * matrix\n         */\n        for (int i = 0, j = tran.length - 1; i != j; i++, j--) {\n            for (int k = 0; k &lt; tran.length; k++) {\n                swap(i, k, j, k, tran);\n            }\n        }\n    }\n\n    public void swap(int a, int b, int c, int d, int[][] arr) {\n        int temp = arr[a][b];\n        arr[a][b] = arr[c][d];\n        arr[c][d] = temp;    \n    }\n\n    /* Method to display the matrix */\n    public void display(int[][] arr) {\n        for (int i = 0; i &lt; arr.length; i++) {\n            for (int j = 0; j &lt; arr.length; j++) {\n                System.out.print(arr[i][j] + " ");\n            }\n            System.out.println();\n        }\n    }\n}\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>1 2 3 \n4 5 6 \n7 8 9 \n\n3 6 9 \n2 5 8 \n1 4 7 \n</code></pre>\n'}, {'answer_id': 35113512, 'author': 'user4313807', 'author_id': 4313807, 'author_profile': 'https://Stackoverflow.com/users/4313807', 'pm_score': -1, 'selected': False, 'text': '<p>Here it is in Java:</p>\n\n<pre><code>public static void rotateInPlace(int[][] m) {\n    for(int layer = 0; layer &lt; m.length/2; layer++){\n        int first = layer;\n        int last = m.length - 1 - first;\n        for(int i = first; i &lt; last; i ++){\n            int offset = i - first;\n            int top = m[first][i];\n            m[first][i] = m[last - offset][first];\n            m[last - offset][first] = m[last][last - offset];\n            m[last][last - offset] = m[i][last];\n            m[i][last] = top;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 35438327, 'author': 'Jack', 'author_id': 828547, 'author_profile': 'https://Stackoverflow.com/users/828547', 'pm_score': 8, 'selected': False, 'text': '<p>I’d like to add a little more detail. In this answer, key concepts are repeated, the pace is slow and intentionally repetitive. The solution provided here is not the most syntactically compact, it is however, intended for those who wish to learn what matrix rotation is and the resulting implementation.</p>\n<p>Firstly, what is a matrix? For the purposes of this answer, a matrix is just a grid where the width and height are the same. Note, the width and height of a matrix can be different, but for simplicity, this tutorial considers only matrices with equal width and height (<em>square matrices</em>). And yes, <em>matrices</em> is the plural of matrix.</p>\n<p>Example matrices are: 2×2, 3×3 or 5×5. Or, more generally, N×N. A 2×2 matrix will have 4 squares because 2×2=4. A 5×5 matrix will have 25 squares because 5×5=25. Each square is called an element or entry. We’ll represent each element with a period (<code>.</code>) in the diagrams below:</p>\n<p>2×2 matrix</p>\n<pre><code>. .\n. .\n</code></pre>\n<p>3×3 matrix</p>\n<pre><code>. . .\n. . .\n. . .\n</code></pre>\n<p>4×4 matrix</p>\n<pre><code>. . . .\n. . . .\n. . . .\n. . . .\n</code></pre>\n<p>So, what does it mean to rotate a matrix? Let’s take a 2×2 matrix and put some numbers in each element so the rotation can be observed:</p>\n<pre><code>0 1\n2 3\n</code></pre>\n<p>Rotating this by 90 degrees gives us:</p>\n<pre><code>2 0\n3 1\n</code></pre>\n<p>We literally turned the whole matrix once to the right just like turning the steering wheel of a car. It may help to think of “tipping” the matrix onto its right side. We want to write a function, in Python, that takes a matrix and rotates it once to the right. The function signature will be:</p>\n<pre><code>def rotate(matrix):\n    # Algorithm goes here.\n</code></pre>\n<p>The matrix will be defined using a two-dimensional array:</p>\n<pre><code>matrix = [\n    [0,1],\n    [2,3]\n]\n</code></pre>\n<p>Therefore the first index position accesses the row. The second index position accesses the column:</p>\n<pre><code>matrix[row][column]\n</code></pre>\n<p>We’ll define a utility function to print a matrix.</p>\n<pre><code>def print_matrix(matrix):\n    for row in matrix:\n        print row\n</code></pre>\n<p>One method of rotating a matrix is to do it a layer at a time. But what is a layer?  Think of an onion. Just like the layers of an onion, as each layer is removed, we move towards the center. Other analogies is a <a href="https://en.wikipedia.org/wiki/Matryoshka_doll" rel="noreferrer">Matryoshka doll</a> or a game of pass-the-parcel.</p>\n<p>The width and height of a matrix dictate the number of layers in that matrix.  Let’s use different symbols for each layer:</p>\n<p>A 2×2 matrix has 1 layer</p>\n<pre><code>. .\n. .\n</code></pre>\n<p>A 3×3 matrix has 2 layers</p>\n<pre><code>. . .\n. x .\n. . .\n</code></pre>\n<p>A 4×4 matrix has 2 layers</p>\n<pre><code>. . . .\n. x x .\n. x x .\n. . . .\n</code></pre>\n<p>A 5×5 matrix has 3 layers</p>\n<pre><code>. . . . .\n. x x x .\n. x O x .\n. x x x .\n. . . . .\n</code></pre>\n<p>A 6×6 matrix has 3 layers</p>\n<pre><code>. . . . . .\n. x x x x .\n. x O O x .\n. x O O x .\n. x x x x .\n. . . . . .\n</code></pre>\n<p>A 7×7 matrix has 4 layers</p>\n<pre><code>. . . . . . .\n. x x x x x .\n. x O O O x .\n. x O - O x .\n. x O O O x .\n. x x x x x .\n. . . . . . .\n</code></pre>\n<p>You may notice that incrementing the width and height of a matrix by one, does not always increase the number of layers. Taking the above matrices and tabulating the layers and dimensions, we see the number of layers increases once for every two increments of width and height:</p>\n<pre><code>+-----+--------+\n| N×N | Layers |\n+-----+--------+\n| 1×1 |      1 |\n| 2×2 |      1 |\n| 3×3 |      2 |\n| 4×4 |      2 |\n| 5×5 |      3 |\n| 6×6 |      3 |\n| 7×7 |      4 |\n+-----+--------+\n</code></pre>\n<p>However, not all layers need rotating. A 1×1 matrix is the same before and after rotation. The central 1×1 layer is always the same before and after rotation no matter how large the overall matrix:</p>\n<pre><code>+-----+--------+------------------+\n| N×N | Layers | Rotatable Layers |\n+-----+--------+------------------+\n| 1×1 |      1 |                0 |\n| 2×2 |      1 |                1 |\n| 3×3 |      2 |                1 |\n| 4×4 |      2 |                2 |\n| 5×5 |      3 |                2 |\n| 6×6 |      3 |                3 |\n| 7×7 |      4 |                3 |\n+-----+--------+------------------+\n</code></pre>\n<p>Given N×N matrix, how can we programmatically determine the number of layers we need to rotate? If we divide the width or height by two and ignore the remainder we get the following results.</p>\n<pre><code>+-----+--------+------------------+---------+\n| N×N | Layers | Rotatable Layers |   N/2   |\n+-----+--------+------------------+---------+\n| 1×1 |      1 |                0 | 1/2 = 0 |\n| 2×2 |      1 |                1 | 2/2 = 1 |\n| 3×3 |      2 |                1 | 3/2 = 1 |\n| 4×4 |      2 |                2 | 4/2 = 2 |\n| 5×5 |      3 |                2 | 5/2 = 2 |\n| 6×6 |      3 |                3 | 6/2 = 3 |\n| 7×7 |      4 |                3 | 7/2 = 3 |\n+-----+--------+------------------+---------+\n</code></pre>\n<p>Notice how <code>N/2</code> matches the number of layers that need to be rotated? Sometimes the number of rotatable layers is one less the total number of layers in the matrix. This occurs when the innermost layer is formed of only one element (i.e. a 1×1 matrix) and therefore need not be rotated. It simply gets ignored.</p>\n<p>We will undoubtedly need this information in our function to rotate a matrix, so let’s add it now:</p>\n<pre><code>def rotate(matrix):\n    size = len(matrix)\n    # Rotatable layers only.\n    layer_count = size / 2\n</code></pre>\n<p>Now we know what layers are and how to determine the number of layers that actually need rotating, how do we isolate a single layer so we can rotate it? Firstly, we inspect a matrix from the outermost layer, inwards, to the innermost layer. A 5×5 matrix has three layers in total and two layers that need rotating:</p>\n<pre><code>. . . . .\n. x x x .\n. x O x .\n. x x x .\n. . . . .\n</code></pre>\n<p>Let’s look at columns first. The position of the columns defining the outermost layer, assuming we count from 0, are 0 and 4:</p>\n<pre><code>+--------+-----------+\n| Column | 0 1 2 3 4 |\n+--------+-----------+\n|        | . . . . . |\n|        | . x x x . |\n|        | . x O x . |\n|        | . x x x . |\n|        | . . . . . |\n+--------+-----------+\n</code></pre>\n<p>0 and 4 are also the positions of the rows for the outermost layer.</p>\n<pre><code>+-----+-----------+\n| Row |           |\n+-----+-----------+\n|   0 | . . . . . |\n|   1 | . x x x . |\n|   2 | . x O x . |\n|   3 | . x x x . |\n|   4 | . . . . . |\n+-----+-----------+\n</code></pre>\n<p>This will always be the case since the width and height are the same. Therefore we can define the column and row positions of a layer with just two values (rather than four).</p>\n<p>Moving inwards to the second layer, the position of the columns are 1 and 3. And, yes, you guessed it, it’s the same for rows. It’s important to understand we had to both increment and decrement the row and column positions when moving inwards to the next layer.</p>\n<pre><code>+-----------+---------+---------+---------+\n|   Layer   |  Rows   | Columns | Rotate? |\n+-----------+---------+---------+---------+\n| Outermost | 0 and 4 | 0 and 4 | Yes     |\n| Inner     | 1 and 3 | 1 and 3 | Yes     |\n| Innermost | 2       | 2       | No      |\n+-----------+---------+---------+---------+\n</code></pre>\n<p>So, to inspect each layer, we want a loop with both increasing and decreasing counters that represent moving inwards, starting from the outermost layer. We’ll call this our ‘layer loop’.</p>\n<pre><code>def rotate(matrix):\n    size = len(matrix)\n    layer_count = size / 2\n\n    for layer in range(0, layer_count):\n        first = layer\n        last = size - first - 1\n        print \'Layer %d: first: %d, last: %d\' % (layer, first, last)\n\n# 5x5 matrix\nmatrix = [\n    [ 0, 1, 2, 3, 4],\n    [ 5, 6, 6, 8, 9],\n    [10,11,12,13,14],\n    [15,16,17,18,19],\n    [20,21,22,23,24]\n]\n\nrotate(matrix)\n</code></pre>\n<p>The code above loops through the (row and column) positions of any layers that need rotating.</p>\n<pre><code>Layer 0: first: 0, last: 4\nLayer 1: first: 1, last: 3\n</code></pre>\n<p>We now have a loop providing the positions of the rows and columns of each layer. The variables <code>first</code> and <code>last</code> identify the index position of the first and last rows and columns. Referring back to our row and column tables:</p>\n<pre><code>+--------+-----------+\n| Column | 0 1 2 3 4 |\n+--------+-----------+\n|        | . . . . . |\n|        | . x x x . |\n|        | . x O x . |\n|        | . x x x . |\n|        | . . . . . |\n+--------+-----------+\n\n+-----+-----------+\n| Row |           |\n+-----+-----------+\n|   0 | . . . . . |\n|   1 | . x x x . |\n|   2 | . x O x . |\n|   3 | . x x x . |\n|   4 | . . . . . |\n+-----+-----------+\n</code></pre>\n<p>So we can navigate through the layers of a matrix. Now we need a way of navigating within a layer so we can move elements around that layer. Note, elements never ‘jump’ from one layer to another, but they do move within their respective layers.</p>\n<p>Rotating each element in a layer rotates the entire layer. Rotating all layers in a matrix rotates the entire matrix. This sentence is very important, so please try your best to understand it before moving on.</p>\n<p>Now, we need a way of actually moving elements, i.e. rotate each element, and subsequently the layer, and ultimately the  matrix. For simplicity, we’ll revert to a 3x3 matrix — that has one rotatable layer.</p>\n<pre><code>0 1 2\n3 4 5\n6 7 8\n</code></pre>\n<p>Our layer loop provides the indexes of the first and last columns, as well as first and last rows:</p>\n<pre><code>+-----+-------+\n| Col | 0 1 2 |\n+-----+-------+\n|     | 0 1 2 |\n|     | 3 4 5 |\n|     | 6 7 8 |\n+-----+-------+\n\n+-----+-------+\n| Row |       |\n+-----+-------+\n|   0 | 0 1 2 |\n|   1 | 3 4 5 |\n|   2 | 6 7 8 |\n+-----+-------+\n</code></pre>\n<p>Because our matrices are always square, we need just two variables, <code>first</code> and <code>last</code>, since index positions are the same for rows and columns.</p>\n<pre><code>def rotate(matrix):\n    size = len(matrix)\n    layer_count = size / 2\n\n    # Our layer loop i=0, i=1, i=2\n    for layer in range(0, layer_count):\n\n        first = layer\n        last = size - first - 1\n        \n        # We want to move within a layer here.\n</code></pre>\n<p>The variables first and last can easily be used to reference the four corners of a matrix. This is because the corners themselves can be defined using various permutations of <code>first</code> and <code>last</code> (with no subtraction, addition or offset of those variables):</p>\n<pre><code>+---------------+-------------------+-------------+\n| Corner        | Position          | 3x3 Values  |\n+---------------+-------------------+-------------+\n| top left      | (first, first)    | (0,0)       |\n| top right     | (first, last)     | (0,2)       |\n| bottom right  | (last, last)      | (2,2)       |\n| bottom left   | (last, first)     | (2,0)       |\n+---------------+-------------------+-------------+\n</code></pre>\n<p>For this reason, we start our rotation at the outer four corners — we’ll rotate those first. Let’s highlight them with <code>*</code>.</p>\n<pre><code>* 1 *\n3 4 5\n* 7 *\n</code></pre>\n<p>We want to swap each <code>*</code> with the <code>*</code> to the right of it. So let’s go ahead a print out our corners defined using only various permutations of <code>first</code> and <code>last</code>:</p>\n<pre><code>def rotate(matrix):\n    size = len(matrix)\n    layer_count = size / 2\n    for layer in range(0, layer_count):\n\n        first = layer\n        last = size - first - 1\n\n        top_left = (first, first)\n        top_right = (first, last)\n        bottom_right = (last, last)\n        bottom_left = (last, first)\n\n        print \'top_left: %s\' % (top_left)\n        print \'top_right: %s\' % (top_right)\n        print \'bottom_right: %s\' % (bottom_right)\n        print \'bottom_left: %s\' % (bottom_left)\n\nmatrix = [\n[0, 1, 2],\n[3, 4, 5],\n[6, 7, 8]\n]\n\nrotate(matrix)\n</code></pre>\n<p>Output should be:</p>\n<pre><code>top_left: (0, 0)\ntop_right: (0, 2)\nbottom_right: (2, 2)\nbottom_left: (2, 0)\n</code></pre>\n<p>Now we could quite easily swap each of the corners from within our layer loop:</p>\n<pre><code>def rotate(matrix):\n    size = len(matrix)\n    layer_count = size / 2\n    for layer in range(0, layer_count):\n        \n        first = layer\n        last = size - first - 1\n\n        top_left = matrix[first][first]\n        top_right = matrix[first][last]\n        bottom_right = matrix[last][last]\n        bottom_left = matrix[last][first]\n\n        # bottom_left -&gt; top_left\n        matrix[first][first] = bottom_left\n        # top_left -&gt; top_right\n        matrix[first][last] = top_left\n        # top_right -&gt; bottom_right\n        matrix[last][last] = top_right\n        # bottom_right -&gt; bottom_left\n        matrix[last][first] = bottom_right\n\n\nprint_matrix(matrix)\nprint \'---------\'\nrotate(matrix)\nprint_matrix(matrix)\n</code></pre>\n<p>Matrix before rotating corners:</p>\n<pre><code>[0, 1, 2]\n[3, 4, 5]\n[6, 7, 8]\n</code></pre>\n<p>Matrix after rotating corners:</p>\n<pre><code>[6, 1, 0]\n[3, 4, 5]\n[8, 7, 2]\n</code></pre>\n<p>Great! We have successfully rotated each corner of the matrix. But, we haven’t rotated the elements in the middle of each layer. Clearly we need a way of iterating within a layer.</p>\n<p>The problem is, the only loop in our function so far (our layer loop), moves to the next layer on each iteration. Since our matrix has only one rotatable layer, the layer loop exits after rotating only the corners. Let’s look at what happens with a larger, 5×5 matrix (where two layers need rotating). The function code has been omitted, but it remains the same as above:</p>\n<pre><code>matrix = [\n[0, 1, 2, 3, 4],\n[5, 6, 7, 8, 9],\n[10, 11, 12, 13, 14],\n[15, 16, 17, 18, 19],\n[20, 21, 22, 23, 24]\n]\nprint_matrix(matrix)\nprint \'--------------------\'\nrotate(matrix)\nprint_matrix(matrix)\n</code></pre>\n<p>The output is:</p>\n<pre><code>[20,  1,  2,  3,  0]\n[ 5, 16,  7,  6,  9]\n[10, 11, 12, 13, 14]\n[15, 18, 17,  8, 19]\n[24, 21, 22, 23,  4]\n</code></pre>\n<p>It shouldn’t be a surprise that the corners of the outermost layer have been rotated, but, you may also notice the corners of the next layer (inwards) have also been rotated. This makes sense. We’ve written code to navigate through layers and also to rotate the corners of each layer. This feels like progress, but unfortunately we must take a step back. It’s just no good moving onto the next layer until the previous (outer) layer has been fully rotated. That is, until each element in the layer has been rotated. Rotating only the corners won’t do!</p>\n<p>Take a deep breath. We need another loop. A nested loop no less. The new, nested loop, will use the <code>first</code> and <code>last</code> variables, plus an offset to navigate within a layer. We’ll call this new loop our ‘element loop’. The element loop will visit each element along the top row, each element down the right side, each element along the bottom row and each element up the left side.</p>\n<ul>\n<li>Moving forwards along the top row requires the column\nindex to be incremented.</li>\n<li>Moving down the right side requires the row index to be\nincremented.</li>\n<li>Moving backwards along the bottom requires the column\nindex to be decremented.</li>\n<li>Moving up the left side requires the row index to be\ndecremented.</li>\n</ul>\n<p>This sounds complex, but it’s made easy because the number of times we increment and decrement to achieve the above remains the same along all four sides of the matrix. For example:</p>\n<ul>\n<li>Move 1 element across the top row.</li>\n<li>Move 1 element down the right side.</li>\n<li>Move 1 element backwards along the bottom row.</li>\n<li>Move 1 element up the left side.</li>\n</ul>\n<p>This means we can use a single variable in combination with the <code>first</code> and <code>last</code> variables to move within a layer. It may help to note that moving across the top row and down the right side both require incrementing. While moving backwards along the bottom and up the left side both require decrementing.</p>\n<pre><code>def rotate(matrix):\n    size = len(matrix)\n    layer_count = size / 2\n    \n    # Move through layers (i.e. layer loop).\n    for layer in range(0, layer_count):\n        \n            first = layer\n            last = size - first - 1\n\n            # Move within a single layer (i.e. element loop).\n            for element in range(first, last):\n            \n                offset = element - first\n\n                # \'element\' increments column (across right)\n                top = (first, element)\n                # \'element\' increments row (move down)\n                right_side = (element, last)\n                # \'last-offset\' decrements column (across left)\n                bottom = (last, last-offset)\n                # \'last-offset\' decrements row (move up)\n                left_side = (last-offset, first)\n\n                print \'top: %s\' % (top)\n                print \'right_side: %s\' % (right_side)\n                print \'bottom: %s\' % (bottom)\n                print \'left_side: %s\' % (left_side)\n</code></pre>\n<p>Now we simply need to assign the top to the right side, right side to the bottom, bottom to the left side, and left side to the top. Putting this all together we get:</p>\n<pre><code>def rotate(matrix):\n    size = len(matrix)\n    layer_count = size / 2\n\n    for layer in range(0, layer_count):\n        first = layer\n        last = size - first - 1\n\n        for element in range(first, last):\n            offset = element - first\n\n            top = matrix[first][element]\n            right_side = matrix[element][last]\n            bottom = matrix[last][last-offset]\n            left_side = matrix[last-offset][first]\n\n            matrix[first][element] = left_side\n            matrix[element][last] = top\n            matrix[last][last-offset] = right_side\n            matrix[last-offset][first] = bottom\n</code></pre>\n<p>Given the matrix:</p>\n<pre><code>0,  1,  2  \n3,  4,  5  \n6,  7,  8 \n</code></pre>\n<p>Our <code>rotate</code> function results in:</p>\n<pre><code>6,  3,  0  \n7,  4,  1  \n8,  5,  2  \n</code></pre>\n'}, {'answer_id': 35527917, 'author': 'Maaz Ashraf', 'author_id': 5956013, 'author_profile': 'https://Stackoverflow.com/users/5956013', 'pm_score': -1, 'selected': False, 'text': '<p>This is simple C code to rotate an array 90degrees. Hope this helps. </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid main(){\nint arr[3][4] =     {85, 2, 85,  4,\n                     85, 6,  7, 85,\n                     9, 85, 11, 12};\n\n\nint arr1[4][3];\n\nint i = 0, j = 0;\n\nfor(i=0;i&lt;4;i++){\nint k = 2;//k = (number of columns in the new array arr1 - 1)\nfor(j=0;j&lt;3;j++){\narr1[i][j]=arr[k][i];\nk--;\n}\n}\n\nint l, m;\nfor(l=0;l&lt;4;l++){\nfor(m=0;m&lt;3;m++){\nprintf("%d ", arr1[l][m]);\n}\nprintf("\\n");\n}\n}//end main\n</code></pre>\n'}, {'answer_id': 37870786, 'author': 'Dudi', 'author_id': 4572425, 'author_profile': 'https://Stackoverflow.com/users/4572425', 'pm_score': -1, 'selected': False, 'text': '<p>My <strong>C#</strong> example code for the great Algorithm sent by @dimple:</p>\n\n<pre><code>/* Author: Dudi,\n * http://www.tutorialspoint.com/compile_csharp_online.php?PID=0Bw_CjBb95KQMYm5qU3VjVGNuZFU */\n\nusing System.IO;\nusing System;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine("Rotating this matrix by 90+ degree:");\n\n        int[,] values=new int[3,3]{{1,2,3}, {4,5,6}, {7,8,9}};\n        //int[,] values=new int[4,4]{{101,102,103, 104}, {105,106, 107,108}, {109, 110, 111, 112}, {113, 114, 115, 116}};\n\n        print2dArray(ref values);\n        transpose2dArray(ref values);\n        //print2dArray(ref values);\n        reverse2dArray(ref values);\n        Console.WriteLine("Output:");\n        print2dArray(ref values);\n    }\n\n    static void print2dArray(ref int[,] matrix){\n        int  nLen = matrix.GetLength(0);\n        int  mLen = matrix.GetLength(1);    \n        for(int n=0; n&lt;nLen; n++){\n            for(int m=0; m&lt;mLen; m++){\n                Console.Write(matrix[n,m] +"\\t");\n            }\n            Console.WriteLine();        \n        }\n        Console.WriteLine();\n    }\n\n    static void transpose2dArray(ref int[,] matrix){\n        int  nLen = matrix.GetLength(0);\n        int  mLen = matrix.GetLength(1);    \n        for(int n=0; n&lt;nLen; n++){\n            for(int m=0; m&lt;mLen; m++){\n                if(n&gt;m){\n                    int tmp = matrix[n,m];\n                    matrix[n,m] = matrix[m,n];\n                    matrix[m,n] = tmp;\n                }\n            }\n        }\n    }\n\n    static void reverse2dArray(ref int[,] matrix){\n        int  nLen = matrix.GetLength(0);\n        int  mLen = matrix.GetLength(1);\n        for(int n=0; n&lt;nLen; n++){\n            for(int m=0; m&lt;mLen/2; m++){                \n                int tmp = matrix[n,m];\n                matrix[n,m] = matrix[n, mLen-1-m];\n                matrix[n,mLen-1-m] = tmp;\n            }\n        }\n    }\n}\n\n/*\nRotating this matrix by 90+ degree:                                                                                                                                             \n1       2       3                                                                                                                                                               \n4       5       6                                                                                                                                                               \n7       8       9                                                                                                                                                               \n\nOutput:                                                                                                                                                                         \n7       4       1                                                                                                                                                               \n8       5       2                                                                                                                                                               \n9       6       3  \n*/\n</code></pre>\n'}, {'answer_id': 38027015, 'author': 'Alexander Bekert', 'author_id': 1322703, 'author_profile': 'https://Stackoverflow.com/users/1322703', 'pm_score': -1, 'selected': False, 'text': '<p>Here is a C# static generic method that does the work for you. Variables are well-named, so you can easily catch the idea of the algorythm.</p>\n\n<pre><code>private static T[,] Rotate180 &lt;T&gt; (T[,] matrix)\n{\n    var height = matrix.GetLength (0);\n    var width = matrix.GetLength (1);\n    var answer = new T[height, width];\n\n    for (int y = 0; y &lt; height / 2; y++)\n    {\n        int topY = y;\n        int bottomY = height - 1 - y;\n        for (int topX = 0; topX &lt; width; topX++)\n        {\n            var bottomX = width - topX - 1;\n            answer[topY, topX] = matrix[bottomY, bottomX];\n            answer[bottomY, bottomX] = matrix[topY, topX];\n        }\n    }\n\n    if (height % 2 == 0)\n        return answer;\n\n    var centerY = height / 2;\n    for (int leftX = 0; leftX &lt; Mathf.CeilToInt(width / 2f); leftX++)\n    {\n        var rightX = width - 1 - leftX;\n        answer[centerY, leftX] = matrix[centerY, rightX];\n        answer[centerY, rightX] = matrix[centerY, leftX];\n    }\n\n    return answer;\n}\n</code></pre>\n'}, {'answer_id': 38142398, 'author': 'Lee.O.', 'author_id': 5976676, 'author_profile': 'https://Stackoverflow.com/users/5976676', 'pm_score': -1, 'selected': False, 'text': '<pre><code>    public static void rotateMatrix(int[,] matrix)\n    {\n        //C#, to rotate an N*N matrix in place\n        int n = matrix.GetLength(0);\n        int layers =  n / 2;\n        int temp, temp2;\n\n        for (int i = 0; i &lt; layers; i++) // for a 5 * 5 matrix, layers will be 2, since at layer three there would be only one element, (2,2), and we do not need to rotate it with itself \n        {\n            int offset = 0;\n            while (offset &lt; n - 2 * i - 1)\n            {\n                // top right &lt;- top left \n                temp = matrix[i + offset, n - i - 1]; //top right value when offset is zero\n                matrix[i + offset, n - i - 1] = matrix[i, i + offset];   \n\n                //bottom right &lt;- top right \n                temp2 = matrix[n - i - 1, n - i - 1 - offset]; //bottom right value when offset is zero\n                matrix[n - i - 1, n - i - 1 - offset] = temp;  \n\n                //bottom left &lt;- bottom right \n                temp = matrix[n - i - 1 - offset, i];\n                matrix[n - i - 1 - offset, i] = temp2;  \n\n                //top left &lt;- bottom left \n                matrix[i, i + offset] = temp; \n\n                offset++;\n            }\n        }\n    }\n</code></pre>\n'}, {'answer_id': 38518519, 'author': 'ThinkTankShark', 'author_id': 5244684, 'author_profile': 'https://Stackoverflow.com/users/5244684', 'pm_score': 1, 'selected': False, 'text': '<p>Great answers but for those who are looking for a DRY JavaScript code for this - both +90 Degrees and -90 Degrees:</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>          // Input: 1 2 3\r\n          //        4 5 6\r\n          //        7 8 9\r\n\r\n          // Transpose: \r\n          //       1 4 7\r\n          //       2 5 8\r\n          //       3 6 9\r\n\r\n          // Output: \r\n          // +90 Degree:\r\n          //       7 4 1\r\n          //       8 5 2\r\n          //       9 6 3\r\n\r\n          // -90 Degree:\r\n          //      3 6 9\r\n          //      2 5 8\r\n          //      1 4 7\r\n\r\n          // Rotate +90\r\n         function rotate90(matrix) {\r\n\r\n           matrix = transpose(matrix);\r\n           matrix.map(function(array) {\r\n             array.reverse();\r\n           });\r\n\r\n           return matrix;\r\n         }\r\n\r\n          // Rotate -90\r\n         function counterRotate90(matrix) {\r\n           var result = createEmptyMatrix(matrix.length);\r\n           matrix = transpose(matrix);\r\n           var counter = 0;\r\n\r\n           for (var i = matrix.length - 1; i &gt;= 0; i--) {\r\n             result[counter] = matrix[i];\r\n             counter++;\r\n           }\r\n\r\n           return result;\r\n         }\r\n\r\n          // Create empty matrix\r\n         function createEmptyMatrix(len) {\r\n           var result = new Array();\r\n           for (var i = 0; i &lt; len; i++) {\r\n             result.push([]);\r\n           }\r\n           return result;\r\n         }\r\n\r\n          // Transpose the matrix\r\n         function transpose(matrix) {\r\n           // make empty array\r\n           var len = matrix.length;\r\n           var result = createEmptyMatrix(len);\r\n\r\n           for (var i = 0; i &lt; matrix.length; i++) {\r\n             for (var j = 0; j &lt; matrix[i].length; j++) {\r\n               var temp = matrix[i][j];\r\n               result[j][i] = temp;\r\n             }\r\n           }\r\n           return result;\r\n         }\r\n\r\n\r\n\r\n          // Test Cases\r\n         var array1 = [\r\n           [1, 2],\r\n           [3, 4]\r\n         ];\r\n         var array2 = [\r\n           [1, 2, 3],\r\n           [4, 5, 6],\r\n           [7, 8, 9]\r\n         ];\r\n         var array3 = [\r\n           [1, 2, 3, 4],\r\n           [5, 6, 7, 8],\r\n           [9, 10, 11, 12],\r\n           [13, 14, 15, 16]\r\n         ];\r\n\r\n          // +90 degress Rotation Tests\r\n\r\n         var test1 = rotate90(array1);\r\n         var test2 = rotate90(array2);\r\n         var test3 = rotate90(array3);\r\n         console.log(test1);\r\n         console.log(test2);\r\n         console.log(test3);\r\n\r\n          // -90 degress Rotation Tests\r\n         var test1 = counterRotate90(array1);\r\n         var test2 = counterRotate90(array2);\r\n         var test3 = counterRotate90(array3);\r\n         console.log(test1);\r\n         console.log(test2);\r\n         console.log(test3);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 39923587, 'author': 'Nicky Feller', 'author_id': 4313927, 'author_profile': 'https://Stackoverflow.com/users/4313927', 'pm_score': -1, 'selected': False, 'text': '<p>Can be done recursively quite cleanly, here is my implementation in golang!</p>\n\n<p>rotate nxn matrix in go golang recursively in place with no additional memory</p>\n\n<pre><code>func rot90(a [][]int) {\n    n := len(a)\n    if n == 1 {\n        return\n    }\n    for i := 0; i &lt; n; i++ {\n        a[0][i], a[n-1-i][n-1] = a[n-1-i][n-1], a[0][i]\n    }\n    rot90(a[1:])\n}\n</code></pre>\n'}, {'answer_id': 40628762, 'author': 'Shrikant Dande', 'author_id': 2449053, 'author_profile': 'https://Stackoverflow.com/users/2449053', 'pm_score': -1, 'selected': False, 'text': '<p>In Java </p>\n\n<pre><code>public class Matrix {\n/* Author Shrikant Dande */\nprivate static void showMatrix(int[][] arr,int rows,int col){\n\n    for(int i =0 ;i&lt;rows;i++){\n        for(int j =0 ;j&lt;col;j++){\n            System.out.print(arr[i][j]+" ");\n        }\n        System.out.println();\n    }\n\n}\n\nprivate static void rotateMatrix(int[][] arr,int rows,int col){\n\n    int[][] tempArr = new int[4][4];\n    for(int i =0 ;i&lt;rows;i++){\n        for(int j =0 ;j&lt;col;j++){\n            tempArr[i][j] = arr[rows-1-j][i];\n            System.out.print(tempArr[i][j]+" ");\n        }\n        System.out.println();\n    }\n\n}\npublic static void main(String[] args) {\n    int[][] arr = { {1,  2,  3,  4},\n             {5,  6,  7,  8},\n             {9,  1, 2, 5},\n             {7, 4, 8, 9}};\n    int rows = 4,col = 4;\n\n    showMatrix(arr, rows, col);\n    System.out.println("------------------------------------------------");\n    rotateMatrix(arr, rows, col);\n\n}\n</code></pre>\n\n<p>}</p>\n'}, {'answer_id': 44095272, 'author': 'Qian Chen', 'author_id': 1663023, 'author_profile': 'https://Stackoverflow.com/users/1663023', 'pm_score': 0, 'selected': False, 'text': '<p>Here is a Javascript solution:</p>\n\n<pre><code>const transpose = m =&gt; m[0].map((x,i) =&gt; m.map(x =&gt; x[i]));\n\na: // original matrix\n123\n456\n789\n\ntranspose(a).reverse(); // rotate 90 degrees counter clockwise \n369\n258\n147\n\ntranspose(a.slice().reverse()); // rotate 90 degrees clockwise \n741\n852\n963\n\ntranspose(transpose(a.slice().reverse()).slice().reverse())\n// rotate 180 degrees \n987\n654\n321\n</code></pre>\n'}, {'answer_id': 44510769, 'author': 'user_3380739', 'author_id': 3380739, 'author_profile': 'https://Stackoverflow.com/users/3380739', 'pm_score': -1, 'selected': False, 'text': '<p>Try My library <a href="https://github.com/landawn/AbacusUtil" rel="nofollow noreferrer">AbacusUtil</a>:</p>\n\n<pre><code>@Test\npublic void test_42519() throws Exception {\n    final IntMatrix matrix = IntMatrix.range(0, 16).reshape(4);\n\n    N.println("======= original =======================");\n    matrix.println();\n    // print out:\n    //    [0, 1, 2, 3]\n    //    [4, 5, 6, 7]\n    //    [8, 9, 10, 11]\n    //    [12, 13, 14, 15]\n\n    N.println("======= rotate 90 ======================");\n    matrix.rotate90().println();\n    // print out:\n    //    [12, 8, 4, 0]\n    //    [13, 9, 5, 1]\n    //    [14, 10, 6, 2]\n    //    [15, 11, 7, 3]\n\n    N.println("======= rotate 180 =====================");\n    matrix.rotate180().println();\n    // print out:\n    //    [15, 14, 13, 12]\n    //    [11, 10, 9, 8]\n    //    [7, 6, 5, 4]\n    //    [3, 2, 1, 0]\n\n    N.println("======= rotate 270 ======================");\n    matrix.rotate270().println();\n    // print out:\n    //    [3, 7, 11, 15]\n    //    [2, 6, 10, 14]\n    //    [1, 5, 9, 13]\n    //    [0, 4, 8, 12]\n\n    N.println("======= transpose =======================");\n    matrix.transpose().println();\n    // print out:\n    //    [0, 4, 8, 12]\n    //    [1, 5, 9, 13]\n    //    [2, 6, 10, 14]\n    //    [3, 7, 11, 15]\n\n    final IntMatrix bigMatrix = IntMatrix.range(0, 10000_0000).reshape(10000);\n\n    // It take about 2 seconds to rotate 10000 X 10000 matrix.\n    Profiler.run(1, 2, 3, "sequential", () -&gt; bigMatrix.rotate90()).printResult();\n\n    // Want faster? Go parallel. 1 second to rotate 10000 X 10000 matrix.\n    final int[][] a = bigMatrix.array();\n    final int[][] c = new int[a[0].length][a.length];\n    final int n = a.length;\n    final int threadNum = 4;\n\n    Profiler.run(1, 2, 3, "parallel", () -&gt; {\n        IntStream.range(0, n).parallel(threadNum).forEach(i -&gt; {\n            for (int j = 0; j &lt; n; j++) {\n                c[i][j] = a[n - j - 1][i];\n            }\n        });\n    }).printResult();\n}\n</code></pre>\n'}, {'answer_id': 44940034, 'author': 'Vladimir Ramik', 'author_id': 4644312, 'author_profile': 'https://Stackoverflow.com/users/4644312', 'pm_score': 1, 'selected': False, 'text': '<p><strong>PHP Solution</strong> for clockwise &amp; counterclockwise</p>\n\n<pre><code>$aMatrix = array(\n    array( 1, 2, 3 ),\n    array( 4, 5, 6 ),\n    array( 7, 8, 9 )\n    );\n\nfunction CounterClockwise( $aMatrix )\n{\n    $iCount  = count( $aMatrix );\n    $aReturn = array();\n    for( $y = 0; $y &lt; $iCount; ++$y )\n    {\n        for( $x = 0; $x &lt; $iCount; ++$x )\n        {\n            $aReturn[ $iCount - $x - 1 ][ $y ] = $aMatrix[ $y ][ $x ];\n        }\n    }\n    return $aReturn;\n}\n\nfunction Clockwise( $aMatrix )\n{\n    $iCount  = count( $aMatrix );\n    $aReturn = array();\n    for( $y = 0; $y &lt; $iCount; ++$y )\n    {\n        for( $x = 0; $x &lt; $iCount; ++$x )\n        {\n            $aReturn[ $x ][ $iCount - $y - 1 ] = $aMatrix[ $y ][ $x ];\n        }\n    }\n    return $aReturn;\n}\n\nfunction printMatrix( $aMatrix )\n{\n    $iCount = count( $aMatrix );\n    for( $x = 0; $x &lt; $iCount; ++$x )\n    {\n        for( $y = 0; $y &lt; $iCount; ++$y )\n        {\n            echo $aMatrix[ $x ][ $y ];\n            echo " ";\n        }\n        echo "\\n";\n    }\n}\nprintMatrix( $aMatrix );\necho "\\n";\n$aNewMatrix = CounterClockwise( $aMatrix );\nprintMatrix( $aNewMatrix );\necho "\\n";\n$aNewMatrix = Clockwise( $aMatrix );\nprintMatrix( $aNewMatrix );\n</code></pre>\n'}, {'answer_id': 49087988, 'author': 'Tom', 'author_id': 882436, 'author_profile': 'https://Stackoverflow.com/users/882436', 'pm_score': 1, 'selected': False, 'text': '<p>C code for matrix transpose &amp; rotate (+/-90, +/-180)</p>\n\n<ul>\n<li>Supports square and non-square matrices, has in-place and copy features</li>\n<li>Supports both 2D arrays and 1D pointers with logical rows/cols</li>\n<li>Unit tests; see tests for examples of usage</li>\n<li>tested gcc -std=c90 -Wall -pedantic, MSVC17</li>\n</ul>\n\n<p>`</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;memory.h&gt;\n#include &lt;assert.h&gt;\n\n/* \n    Matrix transpose &amp; rotate (+/-90, +/-180)\n        Supports both 2D arrays and 1D pointers with logical rows/cols\n        Supports square and non-square matrices, has in-place and copy features\n        See tests for examples of usage\n    tested gcc -std=c90 -Wall -pedantic, MSVC17\n*/\n\ntypedef int matrix_data_t;  /* matrix data type */\n\nvoid transpose(const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);\nvoid transpose_inplace(matrix_data_t* data, int n );\nvoid rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);\nvoid rotate_inplace(int direction, matrix_data_t* data, int n);\nvoid reverse_rows(matrix_data_t* data, int rows, int cols);\nvoid reverse_cols(matrix_data_t* data, int rows, int cols);\n\n/* test/compare fn */\nint test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols );\n\n/* TESTS/USAGE */\nvoid transpose_test() {\n\n    matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };/* 3x3 square, odd length side */\n    matrix_data_t sq3x3_cpy[9];\n    matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };/* 2D 3x3 square */\n    matrix_data_t sq3x3_2D_copy[3][3];\n\n    /* expected test values */\n    const matrix_data_t sq3x3_orig[9] = { 0,1,2,3,4,5,6,7,8 };\n    const matrix_data_t sq3x3_transposed[9] = { 0,3,6,1,4,7,2,5,8};\n\n    matrix_data_t sq4x4[16]= { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };/* 4x4 square, even length*/\n    const matrix_data_t sq4x4_orig[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };\n    const matrix_data_t sq4x4_transposed[16] = { 0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15 };\n\n    /* 2x3 rectangle */\n    const matrix_data_t r2x3_orig[6] = { 0,1,2,3,4,5 };\n    const matrix_data_t r2x3_transposed[6] = { 0,3,1,4,2,5 };\n    matrix_data_t r2x3_copy[6];\n\n    matrix_data_t r2x3_2D[2][3] = { {0,1,2},{3,4,5} };  /* 2x3 2D rectangle */\n    matrix_data_t r2x3_2D_t[3][2];\n\n    /* matrix_data_t r3x2[6] = { 0,1,2,3,4,5 }; */\n    matrix_data_t r3x2_copy[6];\n    /* 3x2 rectangle */\n    const matrix_data_t r3x2_orig[6] = { 0,1,2,3,4,5 };\n    const matrix_data_t r3x2_transposed[6] = { 0,2,4,1,3,5 };\n\n    matrix_data_t r6x1[6] = { 0,1,2,3,4,5 };    /* 6x1 */\n    matrix_data_t r6x1_copy[6];\n\n    matrix_data_t r1x1[1] = { 0 };  /*1x1*/\n    matrix_data_t r1x1_copy[1];\n\n    /* 3x3 tests, 2D array tests */\n    transpose_inplace(sq3x3, 3);    /* transpose in place */\n    assert(!test_cmp(sq3x3, sq3x3_transposed, 3, 3));\n    transpose_inplace(sq3x3, 3);    /* transpose again */\n    assert(!test_cmp(sq3x3, sq3x3_orig, 3, 3));\n\n    transpose(sq3x3, sq3x3_cpy, 3, 3);  /* transpose copy 3x3*/\n    assert(!test_cmp(sq3x3_cpy, sq3x3_transposed, 3, 3));\n\n    transpose((matrix_data_t*)sq3x3_2D, (matrix_data_t*)sq3x3_2D_copy, 3, 3);   /* 2D array transpose/copy */\n    assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_transposed, 3, 3));\n    transpose_inplace((matrix_data_t*)sq3x3_2D_copy, 3);    /* 2D array transpose in place */\n    assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_orig, 3, 3));\n\n    /* 4x4 tests */\n    transpose_inplace(sq4x4, 4);    /* transpose in place */\n    assert(!test_cmp(sq4x4, sq4x4_transposed, 4,4));\n    transpose_inplace(sq4x4, 4);    /* transpose again */\n    assert(!test_cmp(sq4x4, sq4x4_orig, 3, 3));\n\n    /* 2x3,3x2 tests */\n    transpose(r2x3_orig, r2x3_copy, 2, 3);\n    assert(!test_cmp(r2x3_copy, r2x3_transposed, 3, 2));\n\n    transpose(r3x2_orig, r3x2_copy, 3, 2);\n    assert(!test_cmp(r3x2_copy, r3x2_transposed, 2,3));\n\n    /* 2D array */\n    transpose((matrix_data_t*)r2x3_2D, (matrix_data_t*)r2x3_2D_t, 2, 3);\n    assert(!test_cmp((matrix_data_t*)r2x3_2D_t, r2x3_transposed, 3,2));\n\n    /* Nx1 test, 1x1 test */\n    transpose(r6x1, r6x1_copy, 6, 1);\n    assert(!test_cmp(r6x1_copy, r6x1, 1, 6));\n\n    transpose(r1x1, r1x1_copy, 1, 1);\n    assert(!test_cmp(r1x1_copy, r1x1, 1, 1));\n\n}\n\nvoid rotate_test() {\n\n    /* 3x3 square */\n    const matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };\n    const matrix_data_t sq3x3_r90[9] = { 6,3,0,7,4,1,8,5,2 };\n    const matrix_data_t sq3x3_180[9] = { 8,7,6,5,4,3,2,1,0 };\n    const matrix_data_t sq3x3_l90[9] = { 2,5,8,1,4,7,0,3,6 };\n    matrix_data_t sq3x3_copy[9];\n\n    /* 3x3 square, 2D */\n    matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };\n\n    /* 4x4, 2D */\n    matrix_data_t sq4x4[4][4] = { { 0,1,2,3 },{ 4,5,6,7 },{ 8,9,10,11 },{ 12,13,14,15 } };\n    matrix_data_t sq4x4_copy[4][4];\n    const matrix_data_t sq4x4_r90[16] = { 12,8,4,0,13,9,5,1,14,10,6,2,15,11,7,3 };\n    const matrix_data_t sq4x4_l90[16] = { 3,7,11,15,2,6,10,14,1,5,9,13,0,4,8,12 };\n    const matrix_data_t sq4x4_180[16] = { 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 };\n\n    matrix_data_t r6[6] = { 0,1,2,3,4,5 };  /* rectangle with area of 6 (1x6,2x3,3x2, or 6x1) */\n    matrix_data_t r6_copy[6];\n    const matrix_data_t r1x6_r90[6] = { 0,1,2,3,4,5 };\n    const matrix_data_t r1x6_l90[6] = { 5,4,3,2,1,0 };\n    const matrix_data_t r1x6_180[6] = { 5,4,3,2,1,0 };\n\n    const matrix_data_t r2x3_r90[6] = { 3,0,4,1,5,2 };\n    const matrix_data_t r2x3_l90[6] = { 2,5,1,4,0,3 };\n    const matrix_data_t r2x3_180[6] = { 5,4,3,2,1,0 };\n\n    const matrix_data_t r3x2_r90[6] = { 4,2,0,5,3,1 };\n    const matrix_data_t r3x2_l90[6] = { 1,3,5,0,2,4 };\n    const matrix_data_t r3x2_180[6] = { 5,4,3,2,1,0 };\n\n    const matrix_data_t r6x1_r90[6] = { 5,4,3,2,1,0 };\n    const matrix_data_t r6x1_l90[6] = { 0,1,2,3,4,5 };\n    const matrix_data_t r6x1_180[6] = { 5,4,3,2,1,0 };\n\n    /* sq3x3 tests */\n    rotate(90, sq3x3, sq3x3_copy, 3, 3);    /* +90 */\n    assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));\n    rotate(-90, sq3x3, sq3x3_copy, 3, 3);   /* -90 */\n    assert(!test_cmp(sq3x3_copy, sq3x3_l90, 3, 3));\n    rotate(180, sq3x3, sq3x3_copy, 3, 3);   /* 180 */\n    assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));\n    /* sq3x3 in-place rotations */\n    memcpy( sq3x3_copy, sq3x3, 3 * 3 * sizeof(matrix_data_t));\n    rotate_inplace(90, sq3x3_copy, 3);\n    assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));\n    rotate_inplace(-90, sq3x3_copy, 3);\n    assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3)); /* back to 0 orientation */\n    rotate_inplace(180, sq3x3_copy, 3);\n    assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));\n    rotate_inplace(-180, sq3x3_copy, 3);\n    assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3));\n    rotate_inplace(180, (matrix_data_t*)sq3x3_2D, 3);/* 2D test */\n    assert(!test_cmp((matrix_data_t*)sq3x3_2D, sq3x3_180, 3, 3));\n\n    /* sq4x4 */\n    rotate(90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n    assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_r90, 4, 4));\n    rotate(-90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n    assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_l90, 4, 4));\n    rotate(180, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n    assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_180, 4, 4));\n\n    /* r6 as 1x6 */\n    rotate(90, r6, r6_copy, 1, 6);\n    assert(!test_cmp(r6_copy, r1x6_r90, 1, 6));\n    rotate(-90, r6, r6_copy, 1, 6);\n    assert(!test_cmp(r6_copy, r1x6_l90, 1, 6));\n    rotate(180, r6, r6_copy, 1, 6);\n    assert(!test_cmp(r6_copy, r1x6_180, 1, 6));\n\n    /* r6 as 2x3 */\n    rotate(90, r6, r6_copy, 2, 3);\n    assert(!test_cmp(r6_copy, r2x3_r90, 2, 3));\n    rotate(-90, r6, r6_copy, 2, 3);\n    assert(!test_cmp(r6_copy, r2x3_l90, 2, 3));\n    rotate(180, r6, r6_copy, 2, 3);\n    assert(!test_cmp(r6_copy, r2x3_180, 2, 3));\n\n    /* r6 as 3x2 */\n    rotate(90, r6, r6_copy, 3, 2);\n    assert(!test_cmp(r6_copy, r3x2_r90, 3, 2));\n    rotate(-90, r6, r6_copy, 3, 2);\n    assert(!test_cmp(r6_copy, r3x2_l90, 3, 2));\n    rotate(180, r6, r6_copy, 3, 2);\n    assert(!test_cmp(r6_copy, r3x2_180, 3, 2));\n\n    /* r6 as 6x1 */\n    rotate(90, r6, r6_copy, 6, 1);\n    assert(!test_cmp(r6_copy, r6x1_r90, 6, 1));\n    rotate(-90, r6, r6_copy, 6, 1);\n    assert(!test_cmp(r6_copy, r6x1_l90, 6, 1));\n    rotate(180, r6, r6_copy, 6, 1);\n    assert(!test_cmp(r6_copy, r6x1_180, 6, 1));\n}\n\n/* test comparison fn, return 0 on match else non zero */\nint test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols) {\n\n    int r, c;\n\n    for (r = 0; r &lt; rows; ++r) {\n        for (c = 0; c &lt; cols; ++c) {\n            if ((lhs + r * cols)[c] != (rhs + r * cols)[c])\n                return -1;\n        }\n    }\n    return 0;\n}\n\n/*\nReverse values in place of each row in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols\n[A B C] -&gt;  [C B A]\n[D E F]     [F E D]\n*/\nvoid reverse_rows(matrix_data_t* data, int rows, int cols) {\n\n    int r, c;\n    matrix_data_t temp;\n    matrix_data_t* pRow = NULL;\n\n    for (r = 0; r &lt; rows; ++r) {\n        pRow = (data + r * cols);\n        for (c = 0; c &lt; (int)(cols / 2); ++c) { /* explicit truncate */\n            temp = pRow[c];\n            pRow[c] = pRow[cols - 1 - c];\n            pRow[cols - 1 - c] = temp;\n        }\n    }\n}\n\n/*\nReverse values in place of each column in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols\n[A B C] -&gt;  [D E F]\n[D E F]     [A B C]\n*/\nvoid reverse_cols(matrix_data_t* data, int rows, int cols) {\n\n    int r, c;\n    matrix_data_t temp;\n    matrix_data_t* pRowA = NULL;\n    matrix_data_t* pRowB = NULL;\n\n    for (c = 0; c &lt; cols; ++c) {\n        for (r = 0; r &lt; (int)(rows / 2); ++r) { /* explicit truncate */\n            pRowA = data + r * cols;\n            pRowB = data + cols * (rows - 1 - r);\n            temp = pRowA[c];\n            pRowA[c] = pRowB[c];\n            pRowB[c] = temp;\n        }\n    }\n}\n\n/* Transpose NxM matrix to MxN matrix in O(n) time */\nvoid transpose(const matrix_data_t* src, matrix_data_t* dst, int N, int M) {\n\n    int i;\n    for (i = 0; i&lt;N*M; ++i) dst[(i%M)*N + (i / M)] = src[i];    /* one-liner version */\n\n    /*\n    expanded version of one-liner:  calculate XY based on array index, then convert that to YX array index\n    int i,j,x,y;\n    for (i = 0; i &lt; N*M; ++i) {\n    x = i % M;\n    y = (int)(i / M);\n    j = x * N + y;\n    dst[j] = src[i];\n    }\n    */\n\n    /*\n    nested for loop version\n    using ptr arithmetic to get proper row/column\n    this is really just dst[col][row]=src[row][col]\n\n    int r, c;\n\n    for (r = 0; r &lt; rows; ++r) {\n        for (c = 0; c &lt; cols; ++c) {\n            (dst + c * rows)[r] = (src + r * cols)[c];\n        }\n    }\n    */\n}\n\n/*\nTranspose NxN matrix in place\n*/\nvoid transpose_inplace(matrix_data_t* data, int N ) {\n\n    int r, c;\n    matrix_data_t temp;\n\n    for (r = 0; r &lt; N; ++r) {\n        for (c = r; c &lt; N; ++c) { /*start at column=row*/\n                                    /* using ptr arithmetic to get proper row/column */\n                                    /* this is really just\n                                    temp=dst[col][row];\n                                    dst[col][row]=src[row][col];\n                                    src[row][col]=temp;\n                                    */\n            temp = (data + c * N)[r];\n            (data + c * N)[r] = (data + r * N)[c];\n            (data + r * N)[c] = temp;\n        }\n    }\n}\n\n/*\nRotate 1D or 2D src matrix to dst matrix in a direction (90,180,-90)\nPrecondition:  src and dst are 2d matrices with dimensions src[rows][cols] and dst[cols][rows] or 1D pointers with logical rows/cols\n*/\nvoid rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols) {\n\n    switch (direction) {\n    case -90:\n        transpose(src, dst, rows, cols);\n        reverse_cols(dst, cols, rows);\n        break;\n    case 90:\n        transpose(src, dst, rows, cols);\n        reverse_rows(dst, cols, rows);\n        break;\n    case 180:\n    case -180:\n        /* bit copy to dst, use in-place reversals */\n        memcpy(dst, src, rows*cols*sizeof(matrix_data_t));\n        reverse_cols(dst, cols, rows);\n        reverse_rows(dst, cols, rows);\n        break;\n    }\n}\n\n/*\nRotate array in a direction.\nArray must be NxN 2D or 1D array with logical rows/cols\nDirection can be (90,180,-90,-180)\n*/\nvoid rotate_inplace( int direction, matrix_data_t* data, int n) {\n\n    switch (direction) {\n    case -90:\n        transpose_inplace(data, n);\n        reverse_cols(data, n, n);\n        break;\n    case 90:\n        transpose_inplace(data, n);\n        reverse_rows(data, n, n);\n        break;\n    case 180:\n    case -180:\n        reverse_cols(data, n, n);\n        reverse_rows(data, n, n);\n        break;\n    }\n}\n</code></pre>\n\n<p>`</p>\n'}, {'answer_id': 49619504, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Based on the plethora of other answers, I came up with this in C#:</p>\n\n<pre><code>/// &lt;param name="rotation"&gt;The number of rotations (if negative, the &lt;see cref="Matrix{TValue}"/&gt; is rotated counterclockwise; \n/// otherwise, it\'s rotated clockwise). A single (positive) rotation is equivalent to 90° or -270°; a single (negative) rotation is \n/// equivalent to -90° or 270°. Matrices may be rotated by 90°, 180°, or 270° only (or multiples thereof).&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\npublic Matrix&lt;TValue&gt; Rotate(int rotation)\n{\n    var result = default(Matrix&lt;TValue&gt;);\n\n    //This normalizes the requested rotation (for instance, if 10 is specified, the rotation is actually just +-2 or +-180°, but all \n    //correspond to the same rotation).\n    var d = rotation.ToDouble() / 4d;\n    d = d - (int)d;\n\n    var degree = (d - 1d) * 4d;\n\n    //This gets the type of rotation to make; there are a total of four unique rotations possible (0°, 90°, 180°, and 270°).\n    //Each correspond to 0, 1, 2, and 3, respectively (or 0, -1, -2, and -3, if in the other direction). Since\n    //1 is equivalent to -3 and so forth, we combine both cases into one. \n    switch (degree)\n    {\n        case -3:\n        case +1:\n            degree = 3;\n            break;\n        case -2:\n        case +2:\n            degree = 2;\n            break;\n        case -1:\n        case +3:\n            degree = 1;\n            break;\n        case -4:\n        case  0:\n        case +4:\n            degree = 0;\n            break;\n    }\n    switch (degree)\n    {\n        //The rotation is 0, +-180°\n        case 0:\n        case 2:\n            result = new TValue[Rows, Columns];\n            break;\n        //The rotation is +-90°\n        case 1:\n        case 3:\n            result = new TValue[Columns, Rows];\n            break;\n    }\n\n    for (uint i = 0; i &lt; Columns; ++i)\n    {\n        for (uint j = 0; j &lt; Rows; ++j)\n        {\n            switch (degree)\n            {\n                //If rotation is 0°\n                case 0:\n                    result._values[j][i] = _values[j][i];\n                    break;\n                //If rotation is -90°\n                case 1:\n                    //Transpose, then reverse each column OR reverse each row, then transpose\n                    result._values[i][j] = _values[j][Columns - i - 1];\n                    break;\n                //If rotation is +-180°\n                case 2:\n                    //Reverse each column, then reverse each row\n                    result._values[(Rows - 1) - j][(Columns - 1) - i] = _values[j][i];\n                    break;\n                //If rotation is +90°\n                case 3:\n                    //Transpose, then reverse each row\n                    result._values[i][j] = _values[Rows - j - 1][i];\n                    break;\n            }\n        }\n    }\n    return result;\n}\n</code></pre>\n\n<p>Where <code>_values</code> corresponds to a private two-dimensional array defined by <code>Matrix&lt;TValue&gt;</code> (in the form of <code>[][]</code>). <code>result = new TValue[Columns, Rows]</code> is possible via implicit operator overload and converts the two-dimensional array to <code>Matrix&lt;TValue&gt;</code>.\nThe two properties <code>Columns</code> and <code>Rows</code> are public properties that get the number of columns and rows of the current instance:</p>\n\n<pre><code>public uint Columns \n    =&gt; (uint)_values[0].Length;\n\npublic uint Rows \n    =&gt; (uint)_values.Length;\n</code></pre>\n\n<p>Assuming, of course, that you prefer to work with unsigned indices ;-)</p>\n\n<p>All of this allows you to specify how many times it should be rotated and whether it should be rotated left (if less than zero) or right (if greater than zero). You can improve this to check for rotation in actual degrees, but then you\'d want to throw an exception if the value isn\'t a multiple of 90. With that input, you could change the method accordingly:</p>\n\n<pre><code>public Matrix&lt;TValue&gt; Rotate(int rotation)\n{\n    var _rotation = (double)rotation / 90d;\n\n    if (_rotation - Math.Floor(_rotation) &gt; 0)\n    {\n        throw new NotSupportedException("A matrix may only be rotated by multiples of 90.").\n    }\n\n    rotation = (int)_rotation;\n    ...\n}\n</code></pre>\n\n<p>Since a degree is more accurately expressed by <code>double</code> than <code>int</code>, but a matrix can only rotate in multiples of 90, it is far more intuitive to make the argument correspond to something else that can be accurately represented by the data structure used. <code>int</code> is perfect because it can tell you how many times to rotate it up to a certain unit (90) as well as the direction. <code>double</code> may very well be able to tell you that also, but it also includes values that aren\'t supported by this operation (which is inherently counter-intuitive).</p>\n'}, {'answer_id': 50540508, 'author': 'Crashalot', 'author_id': 144088, 'author_profile': 'https://Stackoverflow.com/users/144088', 'pm_score': 0, 'selected': False, 'text': '<p>Based on the community wiki algorithm and <a href="https://stackoverflow.com/a/32922962/144088">this SO answer</a> for transposing arrays, here is a Swift 4 version to rotate some 2D array 90 degrees counter-clockwise. This assumes <code>matrix</code> is a 2D array:</p>\n\n<pre><code>func rotate(matrix: [[Int]]) -&gt; [[Int]] {\n    let transposedPoints = transpose(input: matrix)\n    let rotatedPoints = transposedPoints.map{ Array($0.reversed()) }\n    return rotatedPoints\n}\n\n\nfileprivate func transpose&lt;T&gt;(input: [[T]]) -&gt; [[T]] {\n    if input.isEmpty { return [[T]]() }\n    let count = input[0].count\n    var out = [[T]](repeating: [T](), count: count)\n    for outer in input {\n        for (index, inner) in outer.enumerated() {\n            out[index].append(inner)\n        }\n    }\n\n    return out\n}\n</code></pre>\n'}, {'answer_id': 50983147, 'author': 'Toomtarm Kung', 'author_id': 1483126, 'author_profile': 'https://Stackoverflow.com/users/1483126', 'pm_score': 0, 'selected': False, 'text': '<p>This solution doesn\'t care square or rectangle dimension, you can rotate 4x5 or 5x4 or even 4x4, it doesn\'t care the size as well.\nNote that this implementation creates a new array every time you call rotate90 method, it doesn\'t mutate the original array at all.</p>\n\n<pre><code>public static void main(String[] args) {\n    int[][] a = new int[][] { \n                    { 1, 2, 3, 4 }, \n                    { 5, 6, 7, 8 }, \n                    { 9, 0, 1, 2 }, \n                    { 3, 4, 5, 6 }, \n                    { 7, 8, 9, 0 } \n                  };\n    int[][] rotate180 = rotate90(rotate90(a));\n    print(rotate180);\n}\n\nstatic int[][] rotate90(int[][] a) {\n    int[][] ret = new int[a[0].length][a.length];\n    for (int i = 0; i &lt; a.length; i++) {\n        for (int j = 0; j &lt; a[i].length; j++) {\n            ret[j][a.length - i - 1] = a[i][j];\n        }\n    }\n    return ret;\n}\n\nstatic void print(int[][] array) {\n    for (int i = 0; i &lt; array.length; i++) {\n        System.out.print("[");\n        for (int j = 0; j &lt; array[i].length; j++) {\n            System.out.print(array[i][j]);\n            System.out.print(" ");\n        }\n        System.out.println("]");\n    }\n}\n</code></pre>\n'}, {'answer_id': 61812224, 'author': 'advncd', 'author_id': 996926, 'author_profile': 'https://Stackoverflow.com/users/996926', 'pm_score': 0, 'selected': False, 'text': '<p>I was able to do this with a <strong>single loop</strong>. The time complexity seems like <strong>O(K)</strong> where K is all items of the array. \nHere\'s how I did it in JavaScript:</p>\n\n<p>First off, we represent the n^2 matrix with a single array. Then, iterate through it like this:</p>\n\n<pre class="lang-js prettyprint-override"><code>/**\n * Rotates matrix 90 degrees clockwise\n * @param arr: the source array\n * @param n: the array side (array is square n^2)\n */\nfunction rotate (arr, n) {\n  var rotated = [], indexes = []\n\n  for (var i = 0; i &lt; arr.length; i++) {\n    if (i &lt; n)\n      indexes[i] = i * n + (n - 1)\n    else\n      indexes[i] = indexes[i - n] - 1\n\n    rotated[indexes[i]] = arr[i]\n  }\n  return rotated\n}\n</code></pre>\n\n<p>Basically, we transform the source array indexes:</p>\n\n<p><code>[0,1,2,3,4,5,6,7,8]</code> => <code>[2,5,8,1,4,7,0,3,6]</code></p>\n\n<p>Then, using this transformed <code>indexes</code> array, we place the actual values in the final <code>rotated</code> array.</p>\n\n<p>Here are some test cases:</p>\n\n<pre class="lang-js prettyprint-override"><code>//n=3\nrotate([\n  1, 2, 3,\n  4, 5, 6,\n  7, 8, 9], 3))\n\n//result:\n[7, 4, 1,\n 8, 5, 2,\n 9, 6, 3]\n\n\n//n=4\nrotate([\n  1,  2,  3,  4,\n  5,  6,  7,  8,\n  9,  10, 11, 12,\n  13, 14, 15, 16], 4))\n\n//result:\n[13,  9,  5,  1,\n 14, 10,  6,  2,\n 15, 11,  7,  3,\n 16, 12,  8,  4]\n\n\n//n=5\nrotate([\n  1,  2,  3,  4,  5,\n  6,  7,  8,  9,  10,\n  11, 12, 13, 14, 15,\n  16, 17, 18, 19, 20,\n  21, 22, 23, 24, 25], 5))\n\n//result:\n[21, 16, 11,  6,  1, \n 22, 17, 12,  7,  2, \n 23, 18, 13,  8,  3, \n 24, 19, 14,  9,  4, \n 25, 20, 15, 10,  5]\n</code></pre>\n'}, {'answer_id': 63046730, 'author': 'Meow', 'author_id': 1509571, 'author_profile': 'https://Stackoverflow.com/users/1509571', 'pm_score': 0, 'selected': False, 'text': '<p>In <a href="http://eigen.tuxfamily.org/" rel="nofollow noreferrer">Eigen</a> (C++):</p>\n<pre><code>Eigen::Matrix2d mat;\nmat &lt;&lt;  1, 2,\n        3, 4;\nstd::cout &lt;&lt; mat &lt;&lt; &quot;\\n\\n&quot;;\n\nEigen::Matrix2d r_plus_90 = mat.transpose().rowwise().reverse();\nstd::cout &lt;&lt; r_plus_90 &lt;&lt; &quot;\\n\\n&quot;;\n\nEigen::Matrix2d r_minus_90 = mat.transpose().colwise().reverse();\nstd::cout &lt;&lt; r_minus_90 &lt;&lt; &quot;\\n\\n&quot;;\n\nEigen::Matrix2d r_180 = mat.colwise().reverse().rowwise().reverse(); // +180 same as -180\nstd::cout &lt;&lt; r_180 &lt;&lt; &quot;\\n\\n&quot;;\n</code></pre>\n<p>Output:</p>\n<pre><code>1 2\n3 4\n\n3 1\n4 2\n\n2 4\n1 3\n\n4 3\n2 1\n</code></pre>\n'}, {'answer_id': 63949048, 'author': 'Kapil', 'author_id': 7283174, 'author_profile': 'https://Stackoverflow.com/users/7283174', 'pm_score': 3, 'selected': False, 'text': '<p>A common method to rotate a 2D array clockwise or anticlockwise.</p>\n<ul>\n<li>clockwise rotate\n<ul>\n<li>first reverse up to down, then swap the symmetry\n<pre><code>1 2 3     7 8 9     7 4 1\n4 5 6  =&gt; 4 5 6  =&gt; 8 5 2\n7 8 9     1 2 3     9 6 3\n</code></pre>\n</li>\n</ul>\n</li>\n</ul>\n<pre><code>void rotate(vector&lt;vector&lt;int&gt; &gt; &amp;matrix) {\n    reverse(matrix.begin(), matrix.end());\n    for (int i = 0; i &lt; matrix.size(); ++i) {\n        for (int j = i + 1; j &lt; matrix[i].size(); ++j)\n            swap(matrix[i][j], matrix[j][i]);\n    }\n}\n</code></pre>\n<ul>\n<li>anticlockwise rotate\n<ul>\n<li>first reverse left to right, then swap the symmetry\n<pre><code>1 2 3     3 2 1     3 6 9\n4 5 6  =&gt; 6 5 4  =&gt; 2 5 8\n7 8 9     9 8 7     1 4 7\n</code></pre>\n</li>\n</ul>\n</li>\n</ul>\n<pre><code>void anti_rotate(vector&lt;vector&lt;int&gt; &gt; &amp;matrix) {\n    for (auto vi : matrix) reverse(vi.begin(), vi.end());\n    for (int i = 0; i &lt; matrix.size(); ++i) {\n        for (int j = i + 1; j &lt; matrix[i].size(); ++j)\n            swap(matrix[i][j], matrix[j][i]);\n    }\n}\n</code></pre>\n'}, {'answer_id': 67960479, 'author': 'Michael Dunne', 'author_id': 6171525, 'author_profile': 'https://Stackoverflow.com/users/6171525', 'pm_score': 2, 'selected': False, 'text': '<p>In python:</p>\n<pre><code>import numpy as np\n\na = np.array(\n    [\n        [1, 2, 3, 4],\n        [5, 6, 7, 8],\n        [9, 0, 1, 2],\n        [3, 4, 5, 6]\n    ]\n)\n\nprint(a)\nprint(b[::-1, :].T)\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/42519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736/']