Rotating a NxN matrix in Java

故事扮演 提交于 2021-02-01 05:49:05

问题


This is a question from Cracking the Coding Interview. The solution says that the program rotates the exterior edges, then the interior edges. However, I'm having trouble following the logic of both the for loops.

Could somebody explain the logic of the code (e.g. why they do "layer < n/2" and the four steps of "left -> top" and "bottom -> left" etc)? On a side note, how would one's thought process be when coming up with this during a coding interview?

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

public static void rotate(int[][] matrix, int n) {
    for (int layer = 0; layer < n / 2; ++layer) {
        int first = layer;
        int last = n - 1 - layer;
        for(int i = first; i < last; ++i) {
            int offset = i - first;
            int top = matrix[first][i]; // save top

            // left -> top
            matrix[first][i] = matrix[last-offset][first];          

            // bottom -> left
            matrix[last-offset][first] = matrix[last][last - offset]; 

            // right -> bottom
            matrix[last][last - offset] = matrix[i][last]; 

            // top -> right
            matrix[i][last] = top; // right <- saved top
        }
    }
}

回答1:


Overview

Consider a sample matrix could look like this:

ABCD
EFGH
IJKL
MNOP

For the purposes of my explanation, ABCD is considered as row 0, EFGH is row 1, and so on. The first pixel of row 0 is A.

Also, when I talk about the outer shell, I am referring to:

ABCD
E  H
I  L
MNOP

First let's look at the code that moves the values.

    int top = matrix[first][i]; // save top

The first line caches the value in the top position. This refers to the position on the top row of the matrix identified by [first][i]. Eg: saving the A.

    // left -> top
    matrix[first][i] = matrix[last-offset][first];          

The next part moves the value from the left position into the top position. Eg: taking the M and putting it where the A is.

    // bottom -> left
    matrix[last-offset][first] = matrix[last][last - offset]; 

The next part moves the value from the bottom position into the left position. Eg: taking the P and putting it where the M is.

    // right -> bottom
    matrix[last][last - offset] = matrix[i][last]; 

The next part moves the value from the right position into the bottom position. Eg: taking the D and putting it where the P is.

    // top -> right
    matrix[i][last] = top; // right <- saved top

The last part moves the value from the cache (what was the top position) into the right position. Eg: putting the A from the first step where the D is.

Next the loops.

The outer loop runs from row 0 to half the total number of rows. This is because when you rotate row 0, it also rotates the last row and when you rotate row 1, it also rotates the second-to-last row, and so on.

The inner loop runs from the first pixel position (or column) in the row to the last. Keep in mind that for row 0, this is from pixel 0 to the last pixel, but for row 1, this is from pixel 1 to the second-to-last pixel, since the first and last pixels are rotated as part of row 0.

So the first iteration of the outer loop makes the outer shell rotate. In other words:

ABCD
EFGH
IJKL
MNOP

becomes:

MIEA
NFGB
OJKC
PLHD

See how the outer shell has rotated clockwise, but the inner core has not moved.

Then the second iteration of the outer loop causes the second row to rotate (excluding the first and last pixels) and we end up with:

MIEA
NJFB
OKGC
PLHD



回答2:


I'm writing this answer because even after reading the answer posted by Jason above (it's nice and did resolve a couple of questions I had) it still wasn't clear to me what role is variable "offset" playing in this logic, so spending a couple of hours to understand this I thought to share it with everyone.

There are many variables used here and it's important to understand the significance of each one.

If you look at the variable 'first', it's useless, it's essentially the 'layer' itself, 'first' isn't modified at all in the whole logic. So I have removed 'first' variable (and it works, read ahead).

To understand how each of these values change in every iteration of the inner for loop I have printed the values of these variables. Take a look at the output and understand which values change when we move from one corner to another in the inner for loop, which values stay constant while traversing a single layer and which values change only when we change the layer.

One iteration of inner loop moves one single block. Number of iterations needed to move a single layer will change as we go inwards. The variable 'last' does that job for us, it restricts the inner loop (restricts the inner layer & stops us from going beyond the shell, building upon the nomenclature Jason used)

Time to study the output.

I have used 6x6 matrix.

Input: 

 315 301 755 542 955 33
 943 613 233 880 945 280
 908 609 504 61 849 551
 933 251 706 707 913 917
 479 785 634 97 851 745
 472 348 104 645 17 273

--------------Starting an iteration of OUTER FOR LOOP------------------

--------------Starting an iteration of inner for loop------------------
layer =0
last =5
i =0
buffer = 315
offset = i-layer = 0
Current Status: 

 472 301 755 542 955 315
 943 613 233 880 945 280
 908 609 504 61 849 551
 933 251 706 707 913 917
 479 785 634 97 851 745
 273 348 104 645 17 33
--------------Finished an iteration of inner for loop------------------

--------------Starting an iteration of inner for loop------------------
layer =0
last =5
i =1
buffer = 301
offset = i-layer = 1
Current Status: 

 472 479 755 542 955 315
 943 613 233 880 945 301
 908 609 504 61 849 551
 933 251 706 707 913 917
 17 785 634 97 851 745
 273 348 104 645 280 33
--------------Finished an iteration of inner for loop------------------

--------------Starting an iteration of inner for loop------------------
layer =0
last =5
i =2
buffer = 755
offset = i-layer = 2
Current Status: 

 472 479 933 542 955 315
 943 613 233 880 945 301
 908 609 504 61 849 755
 645 251 706 707 913 917
 17 785 634 97 851 745
 273 348 104 551 280 33
--------------Finished an iteration of inner for loop------------------

--------------Starting an iteration of inner for loop------------------
layer =0
last =5
i =3
buffer = 542
offset = i-layer = 3
Current Status: 

 472 479 933 908 955 315
 943 613 233 880 945 301
 104 609 504 61 849 755
 645 251 706 707 913 542
 17 785 634 97 851 745
 273 348 917 551 280 33
--------------Finished an iteration of inner for loop------------------

--------------Starting an iteration of inner for loop------------------
layer =0
last =5
i =4
buffer = 955
offset = i-layer = 4
Current Status: 

 472 479 933 908 943 315
 348 613 233 880 945 301
 104 609 504 61 849 755
 645 251 706 707 913 542
 17 785 634 97 851 955
 273 745 917 551 280 33
--------------Finished an iteration of inner for loop------------------
--------------Finished an iteration of OUTER FOR LOOP------------------

--------------Starting an iteration of OUTER FOR LOOP------------------

--------------Starting an iteration of inner for loop------------------
layer =1
last =4
i =1
buffer = 613
offset = i-layer = 0
Current Status: 

 472 479 933 908 943 315
 348 785 233 880 613 301
 104 609 504 61 849 755
 645 251 706 707 913 542
 17 851 634 97 945 955
 273 745 917 551 280 33
--------------Finished an iteration of inner for loop------------------

--------------Starting an iteration of inner for loop------------------
layer =1
last =4
i =2
buffer = 233
offset = i-layer = 1
Current Status: 

 472 479 933 908 943 315
 348 785 251 880 613 301
 104 609 504 61 233 755
 645 97 706 707 913 542
 17 851 634 849 945 955
 273 745 917 551 280 33
--------------Finished an iteration of inner for loop------------------

--------------Starting an iteration of inner for loop------------------
layer =1
last =4
i =3
buffer = 880
offset = i-layer = 2
Current Status: 

 472 479 933 908 943 315
 348 785 251 609 613 301
 104 634 504 61 233 755
 645 97 706 707 880 542
 17 851 913 849 945 955
 273 745 917 551 280 33
--------------Finished an iteration of inner for loop------------------
--------------Finished an iteration of OUTER FOR LOOP------------------

--------------Starting an iteration of OUTER FOR LOOP------------------

--------------Starting an iteration of inner for loop------------------
layer =2
last =3
i =2
buffer = 504
offset = i-layer = 0
Current Status: 

 472 479 933 908 943 315
 348 785 251 609 613 301
 104 634 706 504 233 755
 645 97 707 61 880 542
 17 851 913 849 945 955
 273 745 917 551 280 33
--------------Finished an iteration of inner for loop------------------
--------------Finished an iteration of OUTER FOR LOOP------------------

 472 479 933 908 943 315
 348 785 251 609 613 301
 104 634 706 504 233 755
 645 97 707 61 880 542
 17 851 913 849 945 955
 273 745 917 551 280 33

Sorry but there is no way other than to ponder upon how the values of layer, i and offset change to understand what the heck is happening here.

Finally the code

Here is the code where I removed unnecessary first and added all the print statements, in case if anyone wants to play more. This code also has random matrix initialization and printing:

package com.crackingthecodinginterview.assignments.chap1;

public class Problem6RotateMatrix90 {

    public static void main(String args[]){
        int[][] matrix = new int[6][6];
        initializeMatrix(matrix,6);
        System.out.println("Input: ");
        printMatrix(matrix,6);
        rotate(matrix,6);
        printMatrix(matrix,6);
    }

    public static void rotate(int[][] matrix, int n) {
        for (int layer = 0; layer < n / 2; ++layer) {
            System.out.println("\n--------------Starting an iteration of OUTER FOR LOOP------------------");

            int last = n - 1 - layer;
            for(int i = layer; i < last; ++i) {
                int offset = i - layer;
                int buffer = matrix[layer][i]; // save top
                System.out.println("\n--------------Starting an iteration of inner for loop------------------");
                System.out.println("layer ="+layer);

                System.out.println("last ="+last);
                System.out.println("i ="+i);

                System.out.println("buffer = "+buffer);
                System.out.println("offset = i-layer = "+ offset);

                // left -> top
                matrix[layer][i] = matrix[last-offset][layer];          

                // bottom -> left
                matrix[last-offset][layer] = matrix[last][last - offset]; 

                // right -> bottom
                matrix[last][last - offset] = matrix[i][last]; 

                // top -> right
                matrix[i][last] = buffer; // right <- saved top

                //print
                System.out.println("Current Status: ");
                printMatrix(matrix,6);
                System.out.println("--------------Finished an iteration of inner for loop------------------");
            }
            System.out.println("--------------Finished an iteration of OUTER FOR LOOP------------------");

        }
    }

    public static void printMatrix(int[][] matrix,int n){
        System.out.print("\n");
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                System.out.print(" "+matrix[i][j]);
            }
            System.out.print("\n");
        }
    }

    public static void initializeMatrix(int[][] matrix,int n){
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                matrix[i][j]=(int) (Math.random() * 1000);
            }
        }
    }

}



回答3:


Just saw that there is a simpler way to write the code by refactoring "last - offset":

  public static void rotateInPlace90DegreesClockwise(int[][] matrix) {
      int n = matrix.length;
      int half = n / 2;

      for (int layer = 0; layer < half; layer++) {
          int first = layer;
          int last = n - 1 - layer;

          for (int i = first; i < last; i++) {
              int offset = i - first;
              int j = last - offset;
              int top = matrix[first][i]; // save top

              // left -> top
              matrix[first][i] = matrix[j][first];          

              // bottom -> left
              matrix[j][first] = matrix[last][j]; 

              // right -> bottom
              matrix[last][j] = matrix[i][last]; 

              // top -> right
              matrix[i][last] = top; // right <- saved top
          }
      }
  }



回答4:


check this solution to do it in place.

public void rotateMatrix(Pixel[][] matrix) {

    for (int i = 0; i < matrix.length / 2; i++) {

        for (int j = 0; j < matrix.length - 1 - 2 * i; j++) {
            Pixel tmp = matrix[j + i][matrix.length - 1 - i];
            matrix[j + i][matrix.length - 1 - i] = matrix[i][j + i];
            matrix[i][j + i] = matrix[matrix.length - 1 - j - i][i];
            matrix[matrix.length - 1 - j - i][i] = matrix[matrix.length - 1 - i][matrix.length - 1 - j - i];
            matrix[matrix.length - 1 - i][matrix.length - 1 - j - i] = tmp;
        }
    }
}



回答5:


Here's my solution in JavaScript, it swaps values between a row and a column starting from the top-right edge, going inwards until the bottom-leftmost pair is swapped.

function rotateMatrix(arr) {
    var n = arr.length - 1;

    for (var i = 0; i < n; i++) {
        for (var j = 0; j < n - i; j++) {
            var temp = arr[i][j];

            arr[i][j] = arr[n - j][n - i]; // top row
            arr[n - j][n - i] = temp; // right column
        }
    }

    return arr;
}



回答6:


Yes, that code is pretty ugly and hard to read - primarily because the author didn't use very descriptive variable names. I solved that same problem using the same principles (treating the square matrix as a set of concentric squares and then rotating one at a time going from the outer square to the inner square). Here is my solution and the explanation of my thought process.

The Code

I used C#, but the syntax is nearly identical to Java. After copy/pasting, just change a.Length to a.length and it should be syntactically correct Java.

void swap(int[][] a, int g, int h, int i, int j) {
    int temp = a[g][h];
    a[g][h] = a[i][j];
    a[i][j] = temp;
}

int[][] rotateImage(int[][] a) {
    if (a.Length > 1) {
        int topRow = 0, bottomRow = a.Length - 1, leftCol = topRow, rightCol = bottomRow;

        while (topRow < bottomRow && leftCol < rightCol) {
            swap(a, topRow, leftCol, topRow, rightCol);
            swap(a, topRow, leftCol, bottomRow, leftCol);
            swap(a, bottomRow, leftCol, bottomRow, rightCol);

            for (int i = topRow + 1, j = bottomRow - 1; i < bottomRow && j > topRow; i++, j--) {
                swap(a, topRow, i, i, rightCol);
                swap(a, topRow, i, bottomRow, j);
                swap(a, topRow, i, j, leftCol);
            }

            topRow++; leftCol++;
            bottomRow--; rightCol--;
        }
    }

    return a;
}

You may notice that I could potentially get rid of the variables leftCol and rightCol since they are kept equal to topRow and bottomRow respectfully. The reason that I don't is because I feel it makes the code easier to follow.

The Explanation

First, note that if given a 1x1 matrix, we return the original matrix because there is only one pixel which means no rotation is necessary.

Next, imagine we are given the following 2x2 matrix:

1 2
3 4

You could rotate this matrix in three swaps. Top Left -> Top Right, Top Left -> Bottom Left, and Top Left -> Bottom Right.

4 1
2 3

Now imagine we are given the following 3x3 matrix:

1 2 3
4 5 6
7 8 9

Note that the inner square is our old friend the 1x1 matrix. It's important to realize that all square matrices where n > 1 && n % 2 != 0 will eventually reduce down to a 1x1 in the center. Similarly, those where n > 1 && n % 2 == 0 will reduce down to a 2x2 in the center. We can handle both cases the same way.

Again, we will start with the corners of the outer square. We use our familiar previous three swaps: Top Left -> Top Right, Top Left -> Bottom Left, and Top Left -> Bottom Right.

7 2 1
4 5 6
9 8 3

Notice that the matrix is almost rotated; it's just those four pesky values in the centers of the exterior sides. But, also notice that each of those values are just one position away from the corners we rotated. If we continue our pattern of using a fixed starting point for our swaps the same way we did the corners, we could rotate the last four values like so: Top Middle -> Right Middle, Top Middle -> Bottom Middle, and Top Middle -> Left Middle. In terms of indices, "Top Middle" is just "Top Left" plus one. Similarly, "Right Middle" is just "Top Right" plus one. For some of the indices, it makes sense to start at the extreme large index (n - 1) and decrement. I refer to the smaller middle index as i and the larger middle index as j.

7 4 1
8 5 2
9 6 3

It takes three swaps to rotate a 2x2 matrix, six swaps to rotate a 3x3 matrix, and in general it takes n! swaps to rotate a nxn matrix. My while loop rotates the corners for each concentric square in the matrix (and each square is smaller than the previous square), and then my for loop takes care of the values in-between the corners along the edges. It continues like this until either there are no more interior squares to rotate, or the only interior square remaining is a 1x1 matrix.




回答7:


Here's the solution in C#. Every N x N matrix will have floor (N/2) square cycles.

For e.g. - Both 4×4 & 5×5 will have 2 rotatable layers.

Following corner-combination identifies the positions:

(top,left) points to (first,first) --> 0,0
(top,right) points to (first,last) --> 0,n
(bottom,left) points to (last,first) --> n,0
(bottom,right) points to (last,last) --> n,n

Here's the code to rotate matrix by 90 degrees:

    public static void RotateMatrixBy90Degress(int[][] matrix)
    {
        int matrixLen = matrix.Length;
        for (int layer = 0; layer < matrixLen / 2; layer++)
        {
            int first = layer;
            int last = matrixLen - first - 1;

            for (int i = first; i < last; i++)
            {
                int offset = i - first;
                int lastMinusOffset = last - offset;
                // store variable in a temporary variable
                int top = matrix[first][i];

                // move values from left --> top
                matrix[first][i] = matrix[lastMinusOffset][first];

                // move values from bottom --> left
                matrix[lastMinusOffset][first] = matrix[last][lastMinusOffset];

                // move values from right --> bottom
                matrix[last][lastMinusOffset] = matrix[i][last];

                // move values from top  --> right

                matrix[i][last] = top;
            }
        }
    }

Here's the code to generate random numbers in a matrix.

    public static void RotateMatrixImplementation(int len)
    {
        int[][] matrix = new int[len][];
        var random = new Random();
        for (int i = 0; i < matrix.Length; i++)
        {
            matrix[i] = new int[len]; // Create inner array
            for (int j = 0; j < matrix[i].Length; j++)
            {
                //generate random numbers
                matrix[i][j] = random.Next(1, Convert.ToInt32(Math.Pow(len, 3)));
            }
        }
        RotateMatrixBy90Degress(matrix);
    }



回答8:


Here's my 100% result submission to this problem

Firstly I've broken the 2D arraylist into 1D arrayList layerwise, Then rotated 1D matrix then again placed into matrix form While breaking 2D arraylist into 1D arrayList I've saved the positions of element in array so that we can place that rotated matrix at that position

    import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class Solution {
        static List<Integer[]> storePosition = new ArrayList<>();

    public static ArrayList<Integer> rotateOneDArray(List<Integer> arr, int K) {
        int[] A = arr.stream().mapToInt(i -> i).toArray();
        // write your code in Java SE 8

        int r = K % (A.length);
        int[] ans = new int[A.length];
        int y;
        for (int i = 0; i < A.length; i++) {
            y = i - r;
            if (y < 0) {
                y += A.length;
            }
            ans[y] = A[i];
        }

        return (ArrayList<Integer>) Arrays.stream(ans).boxed().collect(Collectors.toList());

    }

    static ArrayList<ArrayList<Integer>> getLinearMatrix(List<List<Integer>> matrix) {
        ArrayList<ArrayList<Integer>> linear = new ArrayList<ArrayList<Integer>>();
        int M = matrix.get(0).size();
        int N = matrix.size();
        int m = M, n = N, i, j, counter = 0;
        Integer[] pos = new Integer[2];
        while (m >= 2 && n >= 2) {
            i = counter;
            j = counter;

            ArrayList<Integer> list = new ArrayList<>((m + n - 2) * 2);

            while (j < M - counter) {
                list.add(matrix.get(i).get(j));
                pos = new Integer[2];
                pos[0] = i;
                pos[1] = j;
                storePosition.add(pos);
                ++j;
            }
            --j;
            ++i;

            while (i < N - counter) {
                list.add(matrix.get(i).get(j));
                pos = new Integer[2];
                pos[0] = i;
                pos[1] = j;
                storePosition.add(pos);
                ++i;
            }
            --i;
            --j;
            while (j >= counter) {
                list.add(matrix.get(i).get(j));
                pos = new Integer[2];
                pos[0] = i;
                pos[1] = j;
                storePosition.add(pos);
                --j;
            }
            ++j;
            --i;
            while (i > counter) {
                list.add(matrix.get(i).get(j));
                pos = new Integer[2];
                pos[0] = i;
                pos[1] = j;
                storePosition.add(pos);
                --i;
            }
            linear.add(list);

            ++counter;
            m -= 2;
            n -= 2;
        }
        return linear;

    }


    // Complete the matrixRotation function below.
    static void matrixRotation(List<List<Integer>> matrix, int r) {

        int m = matrix.get(0).size();
        int n = matrix.size();

        ArrayList<ArrayList<Integer>> linearMat = getLinearMatrix(matrix);
        ArrayList<ArrayList<Integer>> rotatedLinearMat = new ArrayList<ArrayList<Integer>>();

        for (int f = 0; f < linearMat.size(); f++) {

            rotatedLinearMat.add(f, rotateOneDArray(linearMat.get(f), r));
        }

        int p = 0;

        Integer[][] result = new Integer[n][m];
        for (int i = 0; i < rotatedLinearMat.size(); ++i) {
            for (int j = 0; j < rotatedLinearMat.get(i).size(); ++j) {
                result[storePosition.get(p)[0]][storePosition.get(p)[1]] = rotatedLinearMat.get(i).get(j);
                ++p;
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }

    }

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        String[] mnr = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int m = Integer.parseInt(mnr[0]);

        int n = Integer.parseInt(mnr[1]);

        int r = Integer.parseInt(mnr[2]);

        List<List<Integer>> matrix = new ArrayList<>();

        IntStream.range(0, m).forEach(i -> {
            try {
                matrix.add(
                    Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
                        .map(Integer::parseInt)
                        .collect(toList())
                );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        matrixRotation(matrix, r);

        bufferedReader.close();
    }
}



回答9:


The Simple solution is:

int[][] a = { {00,01,02  }, { 10,11,12} ,{20,21,22}};
System.out.println(" lenght " + a.length);

int l = a.length;

for (int i = 0; i <l; i++) {

    for (int j = l - 1; j >= 0; j--) {
        System.out.println(a[j][i]);
    }
}



回答10:


Here is a simple solution that works perfectly for me.

 private int[][] rotateMatrix(int[][] matrix)
    {
        for(int i=0;i<matrix.length-1;i++)
        {
            for(int j =i;j<matrix[0].length;j++)
            {
                if(i!=j) {
                    int temp = matrix[i][j];
                    matrix[i][j] = matrix[j][i];
                    matrix[j][i] = temp;
                }
            }
        }
        return matrix;
    }



回答11:


  /**
 * @param args
 */
public static void main(String[] args) {
    int n = 5; //5x5 matrix
    int[][] matrixInitial = initMatrix(n);
    int[][] matrixFinal = rotate(matrixInitial, n);
    System.out.println(matrixFinal.length);

    int m = 4; //4x4 matrix
    int[][] matrixInitial2 = initMatrix(m);
    int[][] matrixFinal2 = rotate(matrixInitial2, m);
    System.out.println(matrixFinal2.length);
}

private static int[][] rotate(int[][] matrixInitial, int n) {
//it is much like square layers. each layer will be read and rotated
    int layerCount = (n + 1) / 2; 
    System.out.println("n: " + n + " layerCount: " + layerCount);
    int[][] matrixFinal = new int[n][n];
    if (n % 2 == 1) { // for odd # layers the centre does not move
        matrixFinal[n / 2][n / 2] = matrixInitial[n / 2][n / 2];
        layerCount -= 1;
    }

    for (int i = 0; i < layerCount; i++) {
        int width = n - (2 * i); // width of the layer
        System.out.println("width: " + width);
        int[] top = new int[width]; // read top
        for (int j = 0; j < width; j++) {
            top[j] = matrixInitial[i][i + j];
        }
        System.out.println("top: " + Arrays.toString(top));

        //OK TOP TO RIGHT

        for (int j = 0; j < width; j++) { // move top to right 
            matrixFinal[j+i][width-1+i] = top[j];
        }

        int[] tempLeft = new int[width]; // left will be read backwards
        for (int j = 0; j < width; j++) { // reverse the temp
            tempLeft[j] = matrixInitial[i + j][i];
        }

        int[] left = new int[width];
        int indexTemp = 0;
        for (int j = width-1; j >= 0; j--) { // move temp to left
            left[indexTemp++] = tempLeft[j];
        }
        System.out.println("left: " + Arrays.toString(left));

        //OK LEFT TO TOP

        for (int j = 0; j < width; j++) { // move left to top
            matrixFinal[i][j + i] = left[j];
        }

        int[] bottom = new int[width]; read bottom
        for (int j = 0; j < width; j++) {
            bottom[j] = matrixInitial[width - 1 + i][j + i];
        }
        System.out.println("bottom: " + Arrays.toString(bottom));

        //OK BOTTOM TO LEFT

        for (int j = 0; j < width; j++) { // move bottom to left
            matrixFinal[j+i][i] = bottom[j];
        }

        int[] tempRight = new int[width]; // right will be read backwards
        for (int j = 0; j < width; j++) {
            tempRight[j] = matrixInitial[j + i][width - 1 + i];
        }
        int[] right = new int[width]; //reverse the temp
        int indexTemp2 = 0;
        for (int j = width; j > 0; j--) {
            right[indexTemp2++] = tempRight[j - 1];
        }
        System.out.println("right: " + Arrays.toString(right));

        //OK RIGHT TO BOTTOM
        for (int j = 0; j < width; j++) { // move right to bottom
            matrixFinal[width-1+i][j + i] = right[j];
        }

    }
    for (int i = 0; i < n; i++) {
        System.out.println(Arrays.toString(matrixFinal[i]));
    }
    return matrixFinal;
}

private static int[][] initMatrix(int n) { // init the matrix
    int[][] matrix = new int[n][n];
    int fill = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            matrix[i][j] = fill++;
        }
    }

    for (int i = 0; i < n; i++) {
        System.out.println(Arrays.toString(matrix[i]));
    }
    System.out.println("******");
    return matrix;
}


来源:https://stackoverflow.com/questions/25882480/rotating-a-nxn-matrix-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!