简体   繁体   中英

Trying to rotate a 2D array 90 degrees clockwise, but it is going counter-clockwise

public class Rotate
{
public static int[][] rotateArray(int[][] orig)
{
    int[][] neo = new int[orig.length][orig[0].length];
    for(int r = 0; r < orig.length; r++)
    {
        for(int c = 0; c < orig[0].length; c++)
        {
            neo[(orig.length - 1) - c][r] = orig[r][c];
        }
    }
    return neo;
}
}

This question has been answered before, but because I am new to programming and all I know is Java, I was unable to follow the best example I found because it was in C#. Sorry for the duplicate. I named the new rotated array neo because I wanted original and new, but then remembered new can't be used to name variable so I used neo which means new :)

This is a simple modification of your code sample. Notice how the rotated array dimensions and the rotation algebra are changed.

static int[][] rotateArrayCW(int[][] orig) {
    final int rows = orig.length;
    final int cols = orig[ 0 ].length;

    final int[][] neo = new int[ cols ][ rows ];

    for ( int r = 0; r < rows; r++ ) {
        for ( int c = 0; c < cols; c++ ) {
            neo[ c ][ rows - 1 - r ] = orig[ r ][ c ];
        }
    }

    return neo;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM